PYTHON
Efficiently Count Frequencies of Items in a List
Learn to use Python's collections.Counter to quickly count the occurrences of hashable objects in a list or other iterable, ideal for data analysis.
from collections import Counter
data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
item_counts = Counter(data)
print(f"Item counts: {item_counts}")
print(f"Most common item: {item_counts.most_common(1)}")
text = "hello world how are you"
word_counts = Counter(text.split())
print(f"Word counts: {word_counts}")
How it works: `collections.Counter` is a specialized dictionary subclass that helps count hashable objects. When initialized with an iterable (like a list or string), it creates a dictionary-like object mapping unique items to their frequencies. It provides convenient methods such as `most_common()` to efficiently retrieve the most frequent elements and their counts, making it perfect for quick frequency analysis.