logo
Python Data Structures - Interview Questions and Answers
How do you use the Counter class from collections module?
Using the Counter Class from collections in Python

The Counter class from the collections module is a specialized dictionary used for counting hashable objects (e.g., numbers, strings, tuples). It simplifies counting elements in lists, strings, and other iterables.


1. Creating a Counter

Counting Elements in a List
from collections import Counter

# Example list
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

# Create a Counter
counter = Counter(numbers)

print(counter)  
# Output: Counter({4: 4, 3: 3, 2: 2, 1: 1})

* Counts occurrences of each element.


Counting Characters in a String
text = "banana"
char_count = Counter(text)

print(char_count)  
# Output: Counter({'a': 3, 'n': 2, 'b': 1})

2. Accessing Counter Data
print(counter[3])  # Output: 3 (count of 3 in list)
print(counter[5])  # Output: 0 (5 is not in the list)

* Returns 0 for missing elements (instead of KeyError).


3. Most Common Elements
top_counts = counter.most_common(2)  # Get top 2 most common elements
print(top_counts)  
# Output: [(4, 4), (3, 3)]

* Great for finding the most frequent items.


4. Arithmetic & Set Operations

Counters support addition, subtraction, intersection, and union.

c1 = Counter("apple")
c2 = Counter("pear")

# Add counts
print(c1 + c2)  
# Output: Counter({'p': 3, 'a': 2, 'e': 2, 'l': 1, 'r': 1})

# Subtract counts
print(c1 - c2)  
# Output: Counter({'l': 1})

* Useful for bag-of-words models in NLP!


5. Converting Counter to a List
elements = list(counter.elements())
print(elements)  
# Output: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

* Expands the counts back into a list.


6. When to Use Counter?

* Counting words in a document (NLP).
* Finding the most common elements in a dataset.
* Histogram-like frequency analysis.