How to Count the Occurrences of a List Item in Python
Created
Modified
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,
#!/usr/bin/python3
a = ['a', 'b', 'a', 'a']
print(a.count("a"))
3
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,
#!/usr/bin/python3
a = ['a', 'b', 'a', 'a']
count = len(list(filter(lambda x: x=='a', a)))
print(count)
3
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.
#!/usr/bin/python3
# Import module
from collections import Counter
a = ['a', 'b', 'a', 'a']
c = Counter(a)
print(c)
Counter({'a': 3, 'b': 1})