The Python Counter class
from the collections module
is a powerful tool that we can also use for counting the
occurrences of elements in a list.
Let us say that we have a list like the following and want to count the number of times each element appears in there:
my_list = [1, 2, 3, 2, 2, 2, 2]
Now we can simply call the constructor of
Counter and put that list
inside it:
from collections import Counter
my_list = [1, 2, 3, 2, 2, 2, 2]
result = Counter(my_list)
print(result) # Counter({2: 5, 1: 1, 3: 1})
In the example above, we create a
Counter object using a list
of integers. The resulting
Counter object shows that
the number 2 appears 5 times, the number 1 appears once, and
the number 3 appears once.
We can access the frequencies of the elements using the
most_common() method. This
method returns a list of tuples, where each tuple consists of
an element and its frequency. The list is ordered by the
frequencies in descending order:
print(result.most_common()) # [(2, 5), (1, 1), (3, 1)]
In the example above, the
most_common() method
returns
[(2, 5), (1, 1), (3, 1)],
which means that the element 2 appears 5 times, the element 1
appears 1 time, and the element 3 appears 1 time.
Here is the complete example:
from collections import Counter
my_list = [1, 2, 3, 2, 2, 2, 2]
result = Counter(my_list)
print(result) # Counter({2: 5, 1: 1, 3: 1})
print(result.most_common()) # [(2, 5), (1, 1), (3, 1)]
a