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

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

Example

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
print(list_freq)

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

Output

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

Updated on: 07-Aug-2019

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements