PYTHON

Count Element Frequencies in a List

Discover how to quickly count the occurrences of each unique element in a Python list using `collections.Counter`, ideal for statistical analysis of user input or log data.

from collections import Counter

data = ["apple", "banana", "apple", "orange", "banana", "apple", "grape"]

# Count frequencies
fruit_counts = Counter(data)
print("Fruit counts:", fruit_counts)

# Access counts for specific items
print("Count of 'apple':", fruit_counts['apple'])
print("Count of 'banana':", fruit_counts['banana'])
print("Count of 'kiwi' (default 0 for missing):", fruit_counts['kiwi'])

# Get the most common elements
most_common_fruits = fruit_counts.most_common(2)
print("Top 2 most common fruits:", most_common_fruits)
How it works: This snippet utilizes the `Counter` class from Python's `collections` module to efficiently count the frequency of each element in a list. It creates a dictionary-like object where keys are elements and values are their counts. It also demonstrates how to access individual counts and retrieve the `n` most common elements.

Need help integrating this into your project?

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

Hire DigitalCodeLabs