PYTHON
Count Frequencies of Items in a List with `collections.Counter`
Quickly count the occurrences of each unique item in a list using `collections.Counter`, a powerful tool for frequency analysis and data summarization.
from collections import Counter
data_list = ["apple", "banana", "apple", "orange", "banana", "apple"]
item_counts = Counter(data_list)
print(item_counts)
# Expected output: Counter({'apple': 3, 'banana': 2, 'orange': 1})
print(item_counts["apple"])
print(item_counts.most_common(2))
How it works: The `collections.Counter` class is specifically designed for hashable object counting. By passing a list (or any iterable) to its constructor, it automatically tallies the occurrences of each unique element and stores them in a dictionary-like object. This provides a very concise and efficient way to perform frequency analysis and retrieve common items.