How to count the frequency of the elements in an unordered list?
To count element frequencies in a list, Python's collections.Counter
comes to the rescue:
Presto! You get a dictionary-like tally where each item gets counted.
Insights and advanced usage of Counter
Modify counts with math operations
Counter objects play nice with arithmetic operations like +
and -
:
Silicon Valley's top (n) fruits
To find the n
most common items, most_common(n)
is the cool kid in town:
Picking out unique items and counts
.keys()
bags you unique elements, while .values()
delivers their frequencies:
Old school frequency count
When Counter
isn't an option, defaultdict
or dict comprehension come in handy:
Dict comprehension offers a „sleek one-liner“ in Python 2.7+:
Spotting the underdogs
To highlight the least common elements, sort elements()
in ascending order:
The underdogs ('orange'
and 'pear'
) are up front!
When to call upon groupby
When dealing with sorted lists, prefer itertools.groupby
:
Frequency vs elements
Remember: Each frequency in the output list corresponds to a unique value in the input list.
Was this article helpful?