How to Count the Occurrences of a List Item in Python


Using count Method

The str.count() method returns the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. For example,


a = ['a', 'b', 'a', 'a']

Important: this is very slow if you are counting multiple different items.

Each count call goes over the entire list of n elements. Calling count in a loop n times means n * n total checks, which can be catastrophic for performance.

Using filter Method

You can use filter() function to count the occurrences of a list item, it really simple. For example,


a = ['a', 'b', 'a', 'a']
count = len(list(filter(lambda x: x=='a', a)))

Using Counter Method

A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values.


# Import module
from collections import Counter

a = ['a', 'b', 'a', 'a']
c = Counter(a)
Counter({'a': 3, 'b': 1})

Related Tags

#count# #list#