How do I count the occurrences of a list item?
There are a few ways you can count the occurrences of a list item in Python:
You can use a for loop to iterate over the list and increment a counter variable each time you encounter the item you want to count.
You can use the
count()
method of a list, which returns the number of occurrences of an item in the list.You can use the
Collections
module and use aCounter
object, which is a dictionary-like object that counts the occurrences of keys.
Here is an example of how you can use the count()
method:
my_list = [1, 2, 3, 1, 2, 3, 1, 2, 3]
item = 1
count = my_list.count(item)
print(count) # Output: 3
And here is an example of how you can use a Counter
object:
from collections import Counter
my_list = [1, 2, 3, 1, 2, 3, 1, 2, 3]
counter = Counter(my_list)
count = counter[1]
print(count) # Output: 3