The Counter object in Python is a specialized dictionary from the collections module that counts hashable objects, and you use it by importing from collections import Counter and passing an iterable or mapping to it. It automatically tallies each item’s occurrences and stores them as keys with integer counts as values, making tasks like frequency analysis or finding the most common elements a one-liner.
What Is a Counter in Python?
A Counter is a subclass of dict designed specifically for counting. It maps each unique element (the key) to its count (the value). Unlike a regular dictionary where you’d manually write loops like counts[item] = counts.get(item, 0) + 1, a Counter does that work internally. It’s part of the standard library, so no extra installation is needed.
For example, to count characters in a word:
from collections import Counter
c = Counter("hello")
print(c) # Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})
Notice the order: it’s insertion order (Python 3.7+), not sorted by count. The Counter behaves like a dictionary for most operations—you can access c['h'], iterate over keys, and use .get().
How to Create a Counter
You can instantiate a Counter in several ways, depending on your data source:
- From an iterable (list, string, tuple, generator):
Counter(['a', 'b', 'a'])givesCounter({'a': 2, 'b': 1}). - From a dictionary:
Counter({'a': 2, 'b': 1})preserves the given counts. - From keyword arguments:
Counter(a=2, b=1)works as well. - From nothing:
Counter()creates an empty counter, then you can update it later.
Once created, you can add more elements using the update() method: c.update(['a', 'c']) adds to existing counts. Note that update() adds, not replaces—this is different from a regular dictionary’s update().
Common Operations and Methods
The real power of Counter lies in its built-in methods:
most_common([n])– returns a list of (element, count) tuples sorted by count descending. Withn, it returns only the topnelements.elements()– returns an iterator that repeats each element as many times as its count, in arbitrary order. For zero or negative counts, it ignores them.subtract([iterable-or-mapping])– subtracts counts, allowing negative results. This is useful for comparing two distributions.total()– (Python 3.10+) returns the sum of all counts.
Example of most_common:
from collections import Counter
word_counts = Counter("mississippi")
print(word_counts.most_common(2)) # [('i', 4), ('s', 4)]
Note that ties are broken by insertion order, not alphabetically.
Counter vs. Regular Dictionary vs. Other Tools
When should you use a Counter instead of a plain dictionary or defaultdict? The answer depends on what you’re doing:
- Plain dict: if you just need to store counts and don’t care about convenience methods, a dict with a manual loop is fine but more verbose.
- defaultdict(int): this is a common alternative that auto-initializes missing keys to 0. It’s faster for simple incrementing because you don’t have the overhead of Counter’s extra methods. However, it lacks
most_common()and arithmetic operations. - Counter: choose it when you need frequency analysis, comparisons, or the convenience methods. It’s also more readable for counting tasks.
For performance, a plain dict with get or defaultdict can be marginally faster in tight loops, but Counter is optimized in C and is often fast enough for most use cases. In Python 3.10+, Counter has a C implementation that speeds up creation and updates.
Arithmetic and Set-Like Operations
One unique feature of Counter is that it supports addition, subtraction, intersection, and union, which are not available for regular dictionaries.
from collections import Counter
c1 = Counter(a=3, b=1)
c2 = Counter(a=1, b=2)
print(c1 + c2) # Counter({'a': 4, 'b': 3})
print(c1 - c2) # Counter({'a': 2}) # only positive counts remain
print(c1 & c2) # Counter({'a': 1, 'b': 1}) # min of counts
print(c1 | c2) # Counter({'a': 3, 'b': 2}) # max of counts
Subtraction removes elements that go to zero or negative—they are dropped from the result. Intersection and union operate element-wise using min and max respectively. These operations are handy for comparing word frequencies between documents or analyzing overlapping items.
When Not to Use a Counter
Despite its convenience, Counter isn’t always the right tool:
- When you need to preserve order of counts:
Countermaintains insertion order, not sorted order. If you need sorted by count, you must callmost_common()or sort manually. - When counts can be negative:
Counterallows negative counts, but many methods likeelements()ignore them. If you need to track negative values meaningfully, a regular dict ordefaultdictmight be clearer. - When you’re counting a huge stream of data: For extremely large datasets, you might use
itertoolsor specialized libraries likepandasfor performance, butCounterstill works fine for most in-memory tasks. - When you need to count only specific keys: If you need to count only certain items, you can filter the iterable first, but a dict comprehension might be simpler.
Also note that Counter is a dict subclass, so it inherits all dict methods. However, some dict methods like fromkeys() are not supported (it raises NotImplementedError) because it doesn’t make sense to initialize a counter with a single value.
Real-World Examples
Here are a few practical scenarios where Counter shines:
- Word frequency analysis: Count words in a text file to find the most common ones. Example:
Counter(open('file.txt').read().split()).most_common(10). - Survey results: Tally responses from a list of choices.
- Anagram detection: Two strings are anagrams if their
Counters are equal. - Inventory management: Track stock levels by merging counts from different sources using addition.
- Log analysis: Count error types in a log file by splitting lines and counting keywords.
For example, to find the most common IP address in a log:
from collections import Counter
with open('access.log') as f:
ips = [line.split()[0] for line in f]
print(Counter(ips).most_common(1))
Frequently Asked Questions
Is Counter a dict? Yes, Counter is a subclass of dict, so it inherits all dictionary methods. You can use it anywhere a dict is expected, but it adds counting-specific methods.
How do I get the count of a missing key? Like a regular dict, accessing a missing key raises a KeyError. To avoid that, use c.get('missing', 0) or check with in. The Counter itself does not return 0 for missing keys automatically.
Can I use Counter with unhashable types like lists? No, keys must be hashable. If you try to count lists, you’ll get a TypeError. For unhashable items, convert them to tuples or strings first.
How do I convert a Counter back to a list of elements? Use list(c.elements()) to get a list with each element repeated according to its count. For example, list(Counter({'a':2, 'b':1}).elements()) returns ['a', 'a', 'b'] (order may vary).
Is Counter available in Python 2? Yes, Counter was introduced in Python 2.7, but some methods like total() are only in Python 3.10+. Most code works in both, but be aware of version-specific additions.
What’s the difference between Counter and a set? A set stores unique elements with no counts; a Counter stores counts for each element. They serve different purposes—use a set to test membership, use a Counter to count occurrences.
Related
- How to Sum in Excel: 5 Quick Ways
- How to Undo Conditional Formatting in Excel
- Balloons 7 Year Birthday: Ideas, Facts & Safety
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Make an E-Poster in PowerPointTo make an e-poster in PowerPoint, create a single slide at the required dimensions, organize the information into…
- Styles in Word: How They Work and How to Use Them WellStyles in Microsoft Word are named sets of formatting that you can apply to text, paragraphs, tables, or…
- Add a Shared Mailbox in Outlook Without a PasswordYes. You can add a shared mailbox in Outlook without knowing or entering a separate password for it,…
- Excel Shortcut to Insert Copied CellsIn Excel for Microsoft 365 on Windows, copy the cells with Ctrl+C, select the destination, and press Ctrl+Shift++…
- Master Contact List Excel Template: Build and Manage ItA master contact list Excel template is a structured workbook for keeping people’s names, contact details, relationship or…
- Bullseye Glass Firing Schedules: Temperatures and TipsBullseye glass firing schedules depend on the project, glass thickness, kiln, and desired finish; there is no single…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.