What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More
Computer Science

Python Counter (collections.Counter) with Examples

Jul 21, 2026 5 Minutes Read Why Trust Us Why you can trust this guide. Written by working engineers and reviewed by our editorial team under a strict editorial policy for accuracy, clarity and zero bias. Kusum Jain By Kusum Jain Kusum Jain Kusum Jain
I am an avid coder on CodeChef, I partake in hackathons regularly. I am an independent and self-motivated student with a love for coding and experiencing new things.
Python Counter (collections.Counter) with Examples

In Python, Counter is a dictionary subclass from the collections module that counts hashable objects. You pass it an iterable, and it returns a mapping of each element to the number of times it appears.

Counter removes the need to write counting loops by hand. This lesson covers importing Counter from collections, the ways to create one, its main methods, and the counting tasks it is built for.

What Is Counter in Python?

Counter is a class that takes an iterable and returns a dict-like object mapping each element to its count.

# 1. Import the class
from collections import Counter

# 2. Count the elements of a list
votes = ["alice", "bob", "alice", "carol", "alice"]
tally = Counter(votes)
print(tally)  # Outputs: Counter({'alice': 3, 'bob': 1, 'carol': 1})

The result behaves like a dictionary: tally["alice"] returns 3. Elements with higher counts print first.

Python Counter turning a list of votes into a mapping of each name to its count

How to Import Counter From Collections

Counter lives in the collections module of the standard library, so no installation is needed. The usual import is from collections import Counter.

from collections import Counter

print(Counter("mississippi"))  # Outputs: Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})

You can also import collections and write collections.Counter(...). Both forms load the same class.

3 Ways to Create a Counter

1) From a List or Other Iterable

Passing any iterable counts its elements. This is the most common form.

from collections import Counter

orders = ["latte", "espresso", "latte", "mocha", "latte", "espresso"]
print(Counter(orders))  # Outputs: Counter({'latte': 3, 'espresso': 2, 'mocha': 1})

2) From a String

A string is an iterable of characters, so Counter counts each character.

from collections import Counter

print(Counter("bookkeeper"))  # Outputs: Counter({'e': 3, 'o': 2, 'k': 2, 'b': 1, 'p': 1, 'r': 1})

3) From a Dictionary or Keyword Arguments

Existing counts can be loaded directly from a mapping or from keyword arguments.

from collections import Counter

stock = Counter({"laptops": 12, "monitors": 7})
restock = Counter(laptops=4, keyboards=9)
print(stock)    # Outputs: Counter({'laptops': 12, 'monitors': 7})
print(restock)  # Outputs: Counter({'keyboards': 9, 'laptops': 4})

Python Counter Methods

1) The most_common() Method

most_common(n) returns the n elements with the highest counts as (element, count) tuples, ordered from most to least common. With no argument it returns every element.

from collections import Counter

searches = Counter(["python", "sql", "python", "excel", "python", "sql"])
print(searches.most_common(2))  # Outputs: [('python', 3), ('sql', 2)]
most_common(2) returning the two highest counts from a Python Counter as tuples

2) The elements() Method

elements() returns an iterator that repeats each element as many times as its count. Elements with a count below one are skipped.

from collections import Counter

lineup = Counter(guitars=2, drums=1)
print(list(lineup.elements()))  # Outputs: ['guitars', 'guitars', 'drums']

3) The update() Method

update() adds counts from another iterable or mapping instead of replacing them.

from collections import Counter

visits = Counter(["home", "pricing"])
visits.update(["home", "docs"])
print(visits)  # Outputs: Counter({'home': 2, 'pricing': 1, 'docs': 1})

4) The subtract() Method

subtract() decreases counts, and the result can go to zero or below.

from collections import Counter

inventory = Counter(apples=10, pears=4)
inventory.subtract(apples=3, pears=6)
print(inventory)  # Outputs: Counter({'apples': 7, 'pears': -2})

Accessing Counts in a Counter

Reading a count uses dictionary syntax. A missing element returns 0 instead of raising a KeyError, which is the main behavioral difference from a plain dict.

from collections import Counter

badges = Counter(["gold", "silver", "gold"])
print(badges["gold"])      # Outputs: 2
print(badges["platinum"])  # Outputs: 0

To loop over a Counter with each element and its count, use items() like any dictionary.

from collections import Counter

tags = Counter(["bug", "feature", "bug"])
for tag, count in tags.items():
    print(tag, count)
# Outputs:
# bug 2
# feature 1

When to Use Counter in Python

1) Frequency Counts in One Line

Any "how many of each" question is a single Counter call, replacing a loop that builds a dict by hand. Counting an iterable of length n is O(n) time.

2) Finding the Most Common Elements

most_common() answers "top n" questions directly, such as the most frequent words, errors, or purchases.

3) Comparing Two Tallies

Counters support arithmetic: + adds counts, - subtracts and drops non-positive results, & keeps minimums, and | keeps maximums.

from collections import Counter

week1 = Counter(bugs=5, features=2)
week2 = Counter(bugs=3, features=4)
print(week1 + week2)  # Outputs: Counter({'bugs': 8, 'features': 6})
print(week1 - week2)  # Outputs: Counter({'bugs': 2})

Examples of Using Counter in Python

1) Word Frequency in a Sentence

from collections import Counter

quote = "to be or not to be"
frequency = Counter(quote.split())
print(frequency.most_common(2))  # Outputs: [('to', 2), ('be', 2)]

2) The Most Common Value in a List

from collections import Counter

ratings = [5, 4, 5, 3, 5, 4]
top_rating, count = Counter(ratings).most_common(1)[0]
print(top_rating, count)  # Outputs: 5 3

3) Checking for Missing Letters

from collections import Counter

needed = Counter("penguin")
available = Counter("opening")
missing = needed - available
print(missing)  # Outputs: Counter({'u': 1})

Learn More About Python Counter

Counter vs the count() Method

The list method count() returns the count of one value and scans the whole list each call. Counter counts every element in one O(n) pass, so it is the better choice when you need more than one count.

from collections import Counter

colors = ["red", "blue", "red", "green"]
print(colors.count("red"))   # Outputs: 2
print(Counter(colors))       # Outputs: Counter({'red': 2, 'blue': 1, 'green': 1})

Counter vs a Regular Dictionary

Counter is a subclass of dict, so all dict methods work on it. It adds the counting constructor, a zero default for missing keys, the counting methods above, and counter arithmetic.

Sorting a Counter by Count

most_common() already returns elements sorted from highest to lowest count. For ascending order, reverse its result with most_common()[::-1].

Key Takeaways for Python Counter

  • Import - from collections import Counter; it is in the standard library.
  • Counting - one call counts every element of an iterable in O(n) time.
  • Missing keys - return 0 instead of raising KeyError.
  • most_common(n) - the top n elements as (element, count) tuples.
  • Arithmetic - +, -, &, and | combine two Counters by their counts.

Counter answers "how many of each" for a whole collection at once. When you only need the occurrences of a single value, read our lesson on counting occurrences in a Python list.

Kusum Jain
About the author

Kusum Jain

I am an avid coder on CodeChef, I partake in hackathons regularly. I am an independent and self-motivated student with a love for coding and experiencing new things.