Count Occurrences of an Element in a List in Python
Given a list of elements, the task is to count how many times a specific element appears in it. Counting occurrences is a common operation when analyzing data or checking for duplicates.
For example:
a = [1, 3, 2, 6, 3, 2, 8, 2, 9, 2, 7, 3]
Count occurrences of 2 -> 4
Count occurrences of 3 -> 3
Let’s explore different methods to count occurrences of an element in a list one by one.
Using count()
The count() method is built-in and directly returns the number of times an element appears in the list.
a = [1, 3, 2, 6, 3, 2, 8, 2, 9, 2, 7, 3]
print(a.count(3))
Output
3
Using a Loop
In this method, iterate over the list using loop (for loop) and keep a counter variable to count the occurrences. Each time we find the target element, increase the counter by one.
a = [1, 3, 2, 6, 3, 2, 8, 2, 9, 2, 7, 3]
count = 0
for val in a:
if val == 3:
count += 1
print(count)
Output
3
Using operator.countOf()
The operator.countOf() function behaves like the count() method. It takes a sequence and a value and returns the number of times the value appears.
import operator
a = [1, 3, 2, 6, 3, 2, 8, 2, 9, 2, 7, 3]
print(operator.countOf(a, 3))
Output
3
Using Counter from collections
Counter class from the collections module can count occurrences for all elements and returns the results as a dictionary.
from collections import Counter
a = [1, 3, 2, 6, 3, 2, 8, 2, 9, 2, 7, 3]
res = Counter(a)
print(res[3])
Output
3
Note: This method is not efficient for finding occurrence of single element because it requires O(n) extra space to create a new dictionary. But this method is very efficient when finding all occurrences of elements.
Related Articles:
- Python String count() Method
- Count of elements matching particular condition in Python
- Count Occurrences of Specific Value in Pandas Column