PYTHON
Counting Element Frequencies with Counter
Discover Python's collections.Counter to easily count the frequency of items in a list, string, or any iterable, useful for analytics and data aggregation.
from collections import Counter
data = ["apple", "banana", "apple", "orange", "banana", "apple"]
word_counts = Counter(data)
print(f"Word counts: {word_counts}")
# Output: Counter({'apple': 3, 'banana': 2, 'orange': 1})
# Accessing counts
print(f"Count of 'apple': {word_counts['apple']}")
# Output: Count of 'apple': 3
# Most common elements
print(f"Two most common: {word_counts.most_common(2)}")
# Output: [('apple', 3), ('banana', 2)]
# Using on a string
char_counts = Counter("hello world")
print(f"Character counts: {char_counts}")
# Output: Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
# Performing set-like operations (union, intersection)
c1 = Counter(a=3, b=1)
c2 = Counter(a=1, b=2)
print(f"Sum of counters: {c1 + c2}") # Output: Counter({'a': 4, 'b': 3})
How it works: collections.Counter is a subclass of dict designed for counting hashable objects. It efficiently stores elements as dictionary keys and their counts as values. It provides convenient methods like most_common() to retrieve elements ordered by frequency and supports mathematical operations for combining counts, making it perfect for quick data analysis.