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:

  1. 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.

  2. You can use the count() method of a list, which returns the number of occurrences of an item in the list.

  3. You can use the Collections module and use a Counter object, which is a dictionary-like object that counts the occurrences of keys.

Watch a course Python - The Practical Guide

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