Counting repeated values is one of the most common tasks in programming. You may need to find the most frequent words in a document, count product sales, summarize survey answers, or detect duplicate entries. A regular dictionary can solve these problems, but the Python Counter class gives you a shorter and more expressive solution.
Counter belongs to the standard-library collections module. It behaves like a dictionary whose keys are items and whose values are counts. It can build frequency tables from strings, lists, tuples, generators, or mappings, and it includes methods for ranking, updating, subtracting, comparing, and combining counts.
This guide starts with the basics and gradually moves to practical patterns. You will learn how to create counters, access missing values safely, use most_common(), recover repeated elements, combine counters with operators, and apply the class in realistic data-processing tasks.
What Is collections.Counter?
A Counter is a dictionary subclass designed to count hashable objects. Hashable values include strings, numbers, tuples containing hashable values, and many immutable objects. Lists and dictionaries cannot be used directly as Counter keys because they are mutable.
You import it from collections:
from collections import Counter
colors = ["blue", "red", "blue", "green", "blue", "red"]
counts = Counter(colors)
print(counts)
# Counter({'blue': 3, 'red': 2, 'green': 1})The result looks like a dictionary, and most dictionary operations work normally. The key difference is that Counter supplies methods created specifically for frequency data. It also returns zero for a missing key instead of raising KeyError.
print(counts["blue"]) # 3
print(counts["yellow"]) # 0That behavior is useful when a count may not exist yet. For broader examples of specialized containers, see the Python collections module guide. If that page is not part of your current learning path, the Python dataclasses guide also shows how purpose-built types can make code clearer.
Create a Counter from Different Data Sources
Count characters in a string
from collections import Counter
letters = Counter("mississippi")
print(letters)
# Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})Each character becomes a key. Spaces and punctuation are counted too, so normalize text first when necessary.
Count values in a list or tuple
status_codes = [200, 200, 404, 200, 500, 404]
status_counts = Counter(status_codes)
print(status_counts[200]) # 3
print(status_counts[404]) # 2Create a Counter from a mapping
inventory = Counter({"notebook": 12, "pen": 35, "eraser": 8})
print(inventory["pen"]) # 35Create a Counter with keyword arguments
votes = Counter(alice=18, bob=12, carol=9)
print(votes)Keyword arguments are convenient for short examples, but mappings are normally clearer when keys come from files, APIs, or user input.
Find the Most Common Items
most_common() returns item-count pairs ordered from the highest count to the lowest. Pass a number to limit the result.
from collections import Counter
words = "python makes data processing with python easier".split()
frequency = Counter(words)
print(frequency.most_common(2))
# [('python', 2), ('makes', 1)]This method is useful for leaderboards, popular products, common error codes, and word-frequency analysis. It returns a list of tuples, which makes it easy to loop over the result:
for word, amount in frequency.most_common(3):
print(f"{word}: {amount}")When you need to pair or iterate over multiple sequences, the related Python itertools guide explains other memory-efficient iteration tools.
Update and Subtract Counts
update() adds new counts instead of replacing the existing values.
stock = Counter(apples=10, bananas=6)
stock.update(["apples", "apples", "oranges"])
print(stock)
# Counter({'apples': 12, 'bananas': 6, 'oranges': 1})You can also update from another mapping:
stock.update({"bananas": 4, "oranges": 3})
print(stock["bananas"]) # 10subtract() does the opposite. Counter allows zero and negative results, which is useful when representing balances or differences.
stock.subtract({"apples": 5, "oranges": 6})
print(stock)
# apples: 7, bananas: 10, oranges: -2Negative values remain in the Counter until you remove or filter them. Calling unary plus, as in +stock, creates a new Counter containing only positive counts.
Recover Elements with elements()
elements() returns an iterator that repeats every item according to its positive integer count. Zero and negative counts are ignored.
sizes = Counter(small=2, medium=1, large=3)
print(list(sizes.elements()))
# ['small', 'small', 'medium', 'large', 'large', 'large']The order follows when each key first appeared. Because the result is an iterator, convert it to a list only when you actually need all values in memory.
Add, Subtract, Intersect, and Unite Counters
Counter supports operators that make comparisons concise:
first = Counter(red=4, blue=2, green=1)
second = Counter(red=1, blue=3, yellow=5)
print(first + second) # adds counts
print(first - second) # keeps positive differences
print(first & second) # minimum count for shared keys
print(first | second) # maximum count for every key| Operator | Meaning |
|---|---|
+ | Add matching counts. |
- | Subtract and keep only positive results. |
& | Keep the minimum shared count. |
| | Keep the maximum count from either Counter. |
These operations are useful for comparing inventories, permissions, survey groups, or collections of tags.
Get the Total Number of Counted Items
total() returns the sum of all counts:
orders = Counter(book=4, course=7, subscription=3)
print(orders.total()) # 14If negative counts are present, they are included in the sum. On older Python versions without total(), use sum(orders.values()).
Practical Project: Analyze Word Frequency
The following function normalizes a paragraph, removes punctuation, counts words, and returns the most frequent terms. It uses only the standard library.
import re
from collections import Counter
def most_frequent_words(text, limit=10):
normalized = text.lower()
words = re.findall(r"[a-z0-9']+", normalized)
counts = Counter(words)
return counts.most_common(limit)
sample = """
Python is readable. Python is practical, and readable code
is easier to maintain.
"""
for word, count in most_frequent_words(sample, limit=5):
print(f"{word}: {count}")The function uses a clear Python return statement to send the ranked result back to the caller. For production scripts, add Python logging instead of relying only on temporary print calls.
Counter vs. a Regular Dictionary
A normal dictionary remains the right choice when values represent arbitrary information. Use Counter when the values specifically represent quantities or frequencies.
# Manual dictionary approach
counts = {}
for item in ["a", "b", "a"]:
counts[item] = counts.get(item, 0) + 1
# Counter approach
counts = Counter(["a", "b", "a"])The Counter version communicates the intention immediately and gives you ranking and arithmetic methods without extra code. However, a dictionary may be preferable when you need strict control over invalid keys or values that are not numeric counts.
Common Mistakes
- Using unhashable keys: lists and dictionaries cannot be counted directly. Convert a list to a tuple when its contents form a stable key.
- Assuming missing keys raise an error: a missing Counter key returns zero.
- Forgetting negative counts:
subtract()may leave zero or negative entries. - Changing a Counter while iterating over it: iterate over a copy when deleting keys.
- Counting unnormalized text: uppercase, lowercase, punctuation, and extra whitespace can produce separate keys.
Frequently Asked Questions
Does Counter preserve order?
It follows dictionary insertion order. Operations also preserve an order based on when keys first appear in their operands.
Can Counter count floating-point values?
Yes. The items being counted may be hashable floating-point numbers. Counts can also be numeric values other than integers, although methods such as elements() expect positive integer counts.
How do I remove zero or negative counts?
Create a positive-only copy with clean = +counter, or delete unwanted keys explicitly.
How do I get the least common items?
Use counter.most_common() and read from the end of the returned list, or sort counter.items() by the count.
Is Counter part of the standard library?
Yes. Import it from collections; no package installation is required. The official Counter documentation lists its complete API, and the collections module reference covers the related container types.
Conclusion
Python Counter turns frequency analysis into readable, compact code. Start by creating a Counter from an iterable, use most_common() to rank values, and apply update() or subtract() when data arrives in stages. As your use cases grow, Counter arithmetic can compare groups and inventories without complicated loops.
The class is small enough to learn quickly but useful in text processing, analytics, automation, testing, and application monitoring. Whenever you find yourself writing a dictionary loop whose only purpose is increasing a number, Counter is worth considering.






