How to Use Counter for Most Common Elements in Python

This code demonstrates how to find the most frequent elements in a list using Python's Counter class from the collections module.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 13 views 0 copies

Python code

10 lines
Python 3.9+
from collections import Counter

def most_common_elements(items, n=1):
    """Return the n most common elements and their counts."""
    counter = Counter(items)
    return counter.most_common(n)

if __name__ == "__main__":
    data = ["apple", "banana", "apple", "orange", "banana", "apple", "grape"]
    print(most_common_elements(data, 2))

Output

stdout
[('apple', 3), ('banana', 2)]

How it works

The Counter class automatically counts occurrences of each element in the iterable, storing them as a dictionary-like structure with elements as keys and counts as values. The most_common(n) method returns a list of the n most frequent elements as tuples, sorted in descending order of count. This approach is efficient (O(n) for counting) and concise, making it ideal for frequency analysis tasks. The result can be easily unpacked or converted to a dictionary if needed.

Common mistakes

  • Forgetting to import Counter from collections
  • Assuming most_common() returns a dict instead of a list of tuples
  • Not handling the case where n is larger than the number of unique elements

Variations

  1. Use counter.most_common() without arguments to get all elements sorted by frequency
  2. Convert results to a dictionary with dict(counter.most_common(2))

Real-world use cases

  • Analyzing user behavior logs to find the most frequent actions or pages visited.
  • Identifying the most common words in a text corpus for NLP preprocessing.
  • Detecting the most frequent error codes in application monitoring dashboards.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.