Get the frequency of each element in python

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.

  1. The element itself
  2. The frequency of that element

syntax

from collections import Counter
Counter(list).most_common()

The return type is list.

Example

Let us look at this method with an example. I have a list called numbers with some numbers. Some of these numbers are repeated.

frequency of elements in python

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.

Conclusion

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.

Happy coding!