PYTHON
Efficiently Count Item Frequencies
Learn how to quickly count the occurrences of items in a list or any iterable using Python's `collections.Counter`, ideal for data analysis and statistics.
from collections import Counter
data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counts = Counter(data)
print(counts)
# Output: Counter({'apple': 3, 'banana': 2, 'orange': 1})
sentence = "this is a test sentence this is a test"
word_counts = Counter(sentence.split())
print(word_counts)
# Output: Counter({'this': 2, 'is': 2, 'a': 2, 'test': 2, 'sentence': 1})
How it works: `collections.Counter` is a specialized dictionary subclass designed for counting hashable objects. When initialized with an iterable, it automatically tallies the frequency of each element. This provides a remarkably convenient and efficient way to summarize item occurrences, often utilized in analytics, text processing, or log aggregation tasks.