PYTHON
Counting Item Frequencies Efficiently with collections.Counter
Learn how to use Python's collections.Counter to quickly count the frequency of items in a list, string, or any iterable, providing a dictionary-like object of counts.
from collections import Counter
# Example 1: Counting elements in a list
data_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
item_counts = Counter(data_list)
print(f"List item counts: {item_counts}")
# Example 2: Counting characters in a string
text = "hello world"
char_counts = Counter(text)
print(f"String character counts: {char_counts}")
# Accessing most common elements
most_common_items = item_counts.most_common(2)
print(f"Two most common list items: {most_common_items}")
How it works: The collections.Counter class is a subclass of dict that helps count hashable objects. When initialized with an iterable, it creates a dictionary-like object where keys are the elements and values are their counts. It's highly optimized for frequency counting and offers convenient methods like most_common() to retrieve elements by their frequency, making it ideal for analytics or processing textual data.