fruits = ['apple', 'banana', 'orange', 'apple', 'pear', 'apple'] # Count the number of 'apple' in the list apple_count = fruits.count('apple') print(apple_count) # Count the number of 'banana' in the list banana_count = fruits.count('banana') print(banana_count) # Count the number of 'mango' in the list mango_count = fruits.count('mango') print(mango_count)
3 1 0
To count the occurrences of a list item, you can use the count() method on the list. This method takes the item you want to count as an argument and returns the number of times it appears in the list.You can also use a loop to count the occurrences of an item in a list. Here's an example of how to do this:
fruits = ['apple', 'banana', 'orange', 'apple', 'pear', 'apple'] # Initialize a counter counter = 0 # Iterate over the list and count the occurrences of 'apple' for fruit in fruits: if fruit == 'apple': counter += 1 print(counter) # Output: 3
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.
Subscribe to be the first to know when a new Python course is released.