PYTHON
Counting Hashable Objects with Counter
Discover how to efficiently count frequencies of elements in an iterable using Python's collections.Counter data structure.
from collections import Counter
# Count occurrences of elements in a list
color_votes = ["red", "blue", "red", "green", "blue", "red"]
vote_counts = Counter(color_votes)
# Find the 2 most common elements
most_common = vote_counts.most_common(2)
print(most_common)
How it works: Counter is a dictionary subclass designed for counting hashable objects. It automatically builds a frequency map of the input iterable and provides convenient helper methods like most_common() to retrieve top elements.