In Python, Counter is a dictionary-like class in the standard-library collections module that counts how many times each value occurs. Create one with from collections import Counter, then pass it an iterable, such as Counter("banana"), to get counts like {'a': 3, 'n': 2, 'b': 1}.
What Counter Does
A Counter maps elements to integer counts. It is useful for frequency tasks: tallying words, characters, survey answers, product codes, or repeated events. Because it behaves like a dictionary, you can look up a count by key, iterate over its keys, and update values.
Unlike a regular dictionary, a counter gives a missing key the value zero when you read it. This makes it convenient to ask how often a new value has appeared without first checking whether it is present. A missing lookup does not add that key to the counter.
Counter is part of Python’s standard library, so it does not need a separate installation. It is available in supported Python 3 versions through collections.
Creating a Counter
Import the class and pass it an iterable. Each item in that iterable becomes a key, and its number of appearances becomes the value:
from collections import Counter
letters = Counter("mississippi")
print(letters)
print(letters["s"])
print(letters["z"])
The output shows the frequency of each character; the lookup for "z" returns 0. Strings are iterables of individual characters, while a list of words counts whole words:
words = ["pear", "plum", "pear", "apple"]
word_counts = Counter(words)
print(word_counts["pear"]) # 2
You can also build a counter from a mapping of items to counts, or supply keyword arguments when the keys are valid Python identifiers:
from_counts = Counter({"red": 4, "blue": 2})
from_keywords = Counter(red=4, blue=2)
These forms are handy when counts already exist and need to be represented with counter methods. The keyword form is less flexible because keys must follow Python’s rules for keyword argument names.
Reading, Updating, and Removing Counts
Access and assignment work much like a dictionary. A counter can be updated from another iterable or mapping with update(); unlike a dictionary’s update method, this adds incoming counts to existing ones:
inventory = Counter(["pen", "pen", "notebook"])
inventory.update(["pen", "eraser"])
print(inventory["pen"]) # 3
To subtract occurrences, use subtract(). It changes counts in place and, unlike the arithmetic subtraction operator, retains zero and negative results:
inventory.subtract(["pen", "notebook", "notebook"])
print(inventory["notebook"]) # -1
Assign a count directly to replace it. Use del counter[key] to remove a key entirely. Assigning a count of zero does not remove the key; it remains present until deleted. This distinction matters when checking membership or displaying all stored entries.
Finding the Most Common Items
The most_common() method returns a list of (element, count) pairs, ordered from most frequent to least frequent. Pass a positive number to limit the results:
votes = Counter(["yes", "no", "yes", "maybe", "yes", "no"])
print(votes.most_common(2))
This returns [('yes', 3), ('no', 2)]. Calling votes.most_common() without an argument returns all elements in that order. If several elements have the same count, their relative order follows the order in which they were first encountered in the input.
To get the total number of counted occurrences, use sum(counter.values()). This sums the stored counts, including zero or negative values if they are present. By contrast, len(counter) gives the number of distinct keys stored, not the total number of occurrences.
Counter Arithmetic and Comparisons
Counters support addition and subtraction, which combine counts for matching keys. For example, adding two counters makes a combined tally. The arithmetic operators omit results that are zero or negative; this differs from subtract(), which preserves those values.
morning = Counter(["coffee", "tea", "coffee"])
evening = Counter(["tea", "juice"])
print(morning + evening)
Other useful operations include intersection with &, which keeps the smaller count for each shared key, and union with |, which keeps the larger count. These operations are useful for multiset-style comparisons, such as identifying shared inventory quantities. They are not ordinary set operations: repeated items and their counts still matter.
On supported Python 3 versions, counters can also be compared using subset-style comparisons. For instance, Counter(a=1) <= Counter(a=2, b=1) is true because each count on the left is less than or equal to the corresponding count on the right; a missing count is treated as zero for this comparison.
Counter or a Regular Dictionary?
Use Counter when the main job is counting occurrences or combining frequency tables. It offers readable operations such as most_common(), update(), and counter arithmetic. A regular dictionary is a better fit when values represent unrelated data, or when you want a simple mapping without counting-specific behavior.
A common alternative is dict.setdefault() or a dictionary check inside a loop. Those approaches can work, but they require more bookkeeping. For example, a manual tally typically checks whether a key exists before incrementing it. Counter expresses the same purpose directly and reduces that repetitive code.
For a single value, some_list.count(value) may be simpler. However, calling it repeatedly for many different values scans the list repeatedly. A counter tallies the iterable in one pass, which is generally more appropriate when you need the frequencies of many items.
Common Pitfalls and Good Practices
- Confusing keys with occurrences:
len(counter)counts distinct keys;sum(counter.values())totals their counts. - Assuming zero deletes a key: it does not. Use
delif the key should be removed. - Mixing subtraction methods:
subtract()can produce negative counts, while the-operator drops zero and negative results. - Counting the wrong unit: a string counts characters, not words. Split text into words first if word frequency is the goal.
- Ignoring normalization: text such as
"Python"and"python"counts as different values. Convert case or clean data before counting when those forms should match.
For word-frequency work, also consider punctuation and tokenization. Calling text.lower().split() handles basic case differences and whitespace, but it does not remove punctuation reliably: "word" and "word," remain different tokens. More careful text processing may be needed for real documents.
Frequently Asked Questions
Do I need to install Counter?
No. Import it from Python’s standard-library collections module.
How do I count the most frequent item?
Use counter.most_common(1). It returns a list containing the most frequent item and its count, or an empty list if the counter has no entries.
What does Counter return for a missing key?
Reading a missing key returns 0 and does not insert that key into the counter.
Can Counter count objects other than strings?
Yes. It can count hashable elements from iterables, including integers, tuples, and custom objects that are hashable.
Why are some counts negative?
They may result from subtract() or direct assignment. Negative counts are allowed, but arithmetic operations such as + and - omit non-positive results.
Related
- Counter in Python: How to Use collections.Counter
- Counter Dictionary Python: How It Works
- Counter Object Python: How It Works & When to Use It
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 Share a Calendar Event in Microsoft OutlookTo share a calendar event in Outlook, create an invitation and add the people who should receive it,…
- Google Sheets Percentage Increase: Formula & ExamplesTo calculate a percentage increase in Google Sheets, use the formula =(new_value - old_value) / old_value and format…
- Google Sheets Filter Shortcut: Apply a Filter FastIn Google Sheets in a web browser, press Ctrl+Shift+L on Windows, Linux, or ChromeOS to create a filter;…
- PowerPoint Bullseye Diagram Template: How to Make OneA PowerPoint bullseye diagram template is a slide layout made from nested circles that show a central goal…
- Where Is the Transpose Option in Excel?In Excel for Microsoft 365 on Windows, copy the cells you want to turn, select the destination’s top-left…
- Office Contact List Template Excel: Build a Useful DirectoryAn office contact list template in Excel is a structured worksheet for storing coworkers’ names, roles, work contact…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.