How do I count the occurrences of a list item in Python?

Better Stack Team
Updated on February 3, 2023

You can use the count() method of a list to count the number of occurrences of an item in the list.

For example:

my_list = ['a', 'b', 'a', 'c', 'a']
print( my_list.count('a') ) # 3

This will return 3, because the element 'a' occurs 3 times in the list.

You can also use the collections module's Counter class to count the occurrences of items in a list.

For example:

from collections import Counter

my_list = ['a', 'b', 'a', 'c', 'a']
count = Counter(my_list)
print( count['a'] ) # 3

This will return a Counter object with the count of each element in the list. You can then access the count of a specific element using the element as the key.

Note that the count() method only works on lists, while the Counter class can be used to count the occurrences of items in any iterable.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →