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)
to call Counter
with a
to return a dictionary with the values in a
as keys and the count of each item in a
as the values.
Conclusion
To count the frequency of the elements in an unordered list with Python, we can use the collections.Counter
class.