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
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.