![]() |
VOOZH | about |
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.
The count() method is built-in and directly returns the number of times an element appears in the list.
3
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.
3
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.
3
Counter class from the collections module can count occurrences for all elements and returns the results as a dictionary.
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: