PYTHON
Count Element Frequencies Efficiently with Python's Counter
Learn to quickly count the occurrences of items in any iterable using Python's `collections.Counter`, a powerful and concise data structure for frequency analysis.
from collections import Counter
# Example 1: Counting words in a sentence
sentence = "the quick brown fox jumps over the lazy dog quick brown fox"
words = sentence.split()
word_counts = Counter(words)
# Expected: Counter({'quick': 2, 'brown': 2, 'fox': 2, 'the': 2, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1})
# Example 2: Counting elements in a list
data = [1, 2, 3, 1, 2, 4, 5, 1, 3, 2, 6]
item_counts = Counter(data)
# Expected: Counter({1: 3, 2: 3, 3: 2, 4: 1, 5: 1, 6: 1})
# Accessing counts
count_of_one = item_counts[1] # 3
count_of_seven = item_counts[7] # 0 (returns 0 for non-existent items, no KeyError)
# Finding most common elements
most_common_three = item_counts.most_common(3)
# Expected: [(1, 3), (2, 3), (3, 2)]
How it works: `collections.Counter` is a subclass of `dict` specifically designed for counting hashable objects. It provides a convenient and efficient way to tally items in an iterable, access their counts, and even find the most common elements, simplifying various frequency analysis tasks.