Sometimes, we want to count the frequency of the elements in an unordered list with Python.
In this article, we’ll look at how to count the frequency of the elements in an unordered list with Python.
How to count the frequency of the elements in an unordered list with Python?
To count the frequency of the elements in an unordered list with Python, we can use the collections.Counter class.
For instance, we write:
import collections
a = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5]
counter = collections.Counter(a)
print(counter)
We pass in the a array as the argument for the collections.Counter constructor.
This returns a Counter instance that has the items in a as keys and the count of each item as their values.
Therefore, counter is:
Counter({1: 4, 2: 4, 3: 2, 5: 2, 4: 1})
Conclusion
To count the frequency of the elements in an unordered list with Python, we can use the collections.Counter class.