In this article, we shall see how to get the frequency of each element in a list using python. We will be using the built-in module in python called collections for this purpose.
What does this module do?
The collection module has a class called Counter. This class has a method called most_common(). This will take a Counter object as input and return us a list of tuples.
Each tuple has two values.
- The element itself
- The frequency of that element
from collections import Counter Counter(list).most_common()
The return type is list.
Let us look at this method with an example. I have a list called numbers with some numbers. Some of these numbers are repeated.
The output of the above code is,
[(5, 4), (3, 3), (10, 3), (1, 2), (2, 1), (6, 1)]
It also sorts the resulting list based on the frequency.
This is the best possible way to get the frequency of each element along with the element itself that too in a sorted list. This will come in handy if you want to plot graphs.