PYTHON

Count Item Frequencies in a Python List using `collections.Counter`

Discover how to quickly and efficiently count the occurrences of items in any list using Python's `collections.Counter`. Perfect for data analysis, statistics, and finding popular items.

from collections import Counter

items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple', 'grape']
numbers = [1, 2, 2, 3, 3, 3, 4]

# Count frequencies for strings
item_counts = Counter(items)
# print(item_counts) # Counter({'apple': 3, 'banana': 2, 'orange': 1, 'grape': 1})

# Count frequencies for numbers
number_counts = Counter(numbers)
# print(number_counts) # Counter({3: 3, 2: 2, 1: 1, 4: 1})

# Accessing counts
# print(item_counts['apple']) # 3

# Get the most common items
# print(item_counts.most_common(2)) # [('apple', 3), ('banana', 2)]
How it works: The `collections.Counter` class provides a convenient way to count hashable objects. It's a subclass of `dict` that stores elements as keys and their counts as values. This snippet shows how to initialize a `Counter` with a list, access individual counts, and use the `most_common()` method to retrieve elements and their counts in descending order of frequency.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs