Count frequencies of all elements in array in Python using collections module

As python allows duplicate elements in a list we can have one element present multiple Times. The frequency of elements in a list indicates how many times an element occurs in a list. In this article we use the Counter function of the collections module to find out the frequency of each item in a list.


Syntax: Counter(list)
Where list is an iterable in python


The below code uses the Counter() to keep track of frequency and items() to iterate over each item in the result of counter function for printing in a formatted manner.

from collections import Counter
list = ['Mon', 'Tue', 'Wed', 'Mon','Mon','Tue']

# Finding count of each element
list_freq= (Counter(list))

#Printing result of counter

# Printing it using loop
for key, value in list_freq.items():
   print(key, " has count ", value)


Running the above code gives us the following result −

Counter({'Mon': 3, 'Tue': 2, 'Wed': 1})
Mon has count 3
Tue has count 2
Wed has count 1