PYTHON
Count Frequencies and Find Most Common Items with collections.Counter
Efficiently count occurrences of elements in a list, string, or iterable and quickly identify the most frequent items using Python's specialized collections.Counter data structure.
from collections import Counter
# Example 1: Counting words in a sentence
sentence = "apple banana apple orange banana apple grape"
words = sentence.split()
word_counts = Counter(words)
print(f"Word counts: {word_counts}")
# Finding the 2 most common words
most_common_words = word_counts.most_common(2)
print(f"2 most common words: {most_common_words}")
# Example 2: Counting characters in a string
char_counts = Counter("programming")
print(f"Character counts: {char_counts}")
# Performing arithmetic operations (addition/subtraction of counts)
c1 = Counter('aabbc')
c2 = Counter('bbcd')
print(f"Combined counts (c1 + c2): {c1 + c2}")
print(f"Difference counts (c1 - c2): {c1 - c2}")
How it works: The `collections.Counter` is a subclass of `dict` designed for counting hashable objects. It's a convenient and fast way to count element frequencies in any iterable. Its `most_common(n)` method efficiently returns a list of the n most common elements and their counts. It also supports useful arithmetic operations like addition and subtraction for combining or differentiating counts from multiple Counters.