collections.Counter is a Python container that counts the occurrences of hashable elements, and you create one by passing an iterable or mapping to Counter(). For example, Counter('abracadabra') returns Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}), giving you an instant frequency table with no manual loops.
What Is a Counter?
A Counter is a subclass of the built-in dict designed specifically for counting. It maps each unique element to its count, just like a dictionary maps keys to values. The key difference is that Counter provides extra methods and behaviors tailored for tallying, such as most_common(), elements(), and arithmetic operations between counters. Because it inherits from dict, it supports all normal dictionary operations like keys(), values(), and items(), but it adds conveniences that make frequency counting much cleaner.
You import it from the collections module: from collections import Counter. It is part of the Python standard library, so no extra installation is needed.
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']) → Counter({'a': 2, 'b': 1}) - From a dictionary (keys become elements, values become counts):
Counter({'a': 3, 'b': 1}) - From keyword arguments:
Counter(a=3, b=1) - From nothing:
Counter()creates an empty counter, which you can then fill withupdate().
For example, to count words in a sentence:
sentence = "the cat and the dog and the bird"
word_counts = Counter(sentence.split())
print(word_counts) # Counter({'the': 3, 'and': 2, 'cat': 1, 'dog': 1, 'bird': 1})
Note that the elements must be hashable (immutable types like strings, numbers, tuples). Lists and dictionaries cannot be keys because they are unhashable.
Key Methods and Operations
Counter provides several methods beyond standard dict methods:
most_common([n])– returns a list of the n most common elements and their counts, sorted by count descending. If n is omitted, returns all elements. Example:Counter('abracadabra').most_common(2)returns[('a', 5), ('b', 2)].elements()– returns an iterator that yields each element repeated as many times as its count, in arbitrary order. For counts less than 1, elements are ignored. Example:list(Counter(a=2, b=1).elements())returns['a', 'a', 'b'].update(iterable_or_mapping)– adds counts from another iterable or mapping. Example:c = Counter(a=1); c.update(['a', 'b']) → Counter({'a': 2, 'b': 1}).subtract(iterable_or_mapping)– subtracts counts, but does not remove elements that go to zero or negative; those remain with negative counts. Example:c = Counter(a=3, b=1); c.subtract(a=1) → Counter({'a': 2, 'b': 1}).
Also, you can access counts like a dictionary: c['a'] returns the count, and if the key is missing, it returns 0 (not a KeyError). This is a major convenience for counting tasks.
Arithmetic and Comparisons
Counter supports addition, subtraction, intersection, and union with other counters, which is useful for combining or comparing frequency data.
- Addition (
+): adds counts, keeping only positive counts. Example:Counter(a=2) + Counter(a=1, b=1)→Counter({'a': 3, 'b': 1}). - Subtraction (
-): subtracts counts, keeping only positive counts (elements with zero or negative results are dropped). Example:Counter(a=3, b=1) - Counter(a=1)→Counter({'a': 2, 'b': 1}). - Intersection (
&): takes the minimum count for each element. Example:Counter(a=3, b=1) & Counter(a=1, b=2)→Counter({'a': 1, 'b': 1}). - Union (
|): takes the maximum count for each element. Example:Counter(a=3, b=1) | Counter(a=1, b=2)→Counter({'a': 3, 'b': 2}).
These operations are handy for tasks like comparing word frequencies across documents or merging inventory counts.
Common Use Cases and Examples
Counter is used in many real-world scenarios where frequency matters:
- Finding the most common elements in a list:
Counter(my_list).most_common(1)gives the mode. - Counting characters in a string for text analysis or password strength checks.
- Counting items in a log file to see which error codes appear most often.
- Building a histogram of data values.
- Checking for anagrams: two strings are anagrams if their Counters are equal.
For example, to check if two words are anagrams:
def is_anagram(word1, word2):
return Counter(word1) == Counter(word2)
print(is_anagram('listen', 'silent')) # True
Another example: finding the top 3 most frequent words in a text file:
from collections import Counter
with open('text.txt') as f:
words = f.read().split()
common = Counter(words).most_common(3)
print(common)
Performance and Limitations
Counter is implemented in pure Python and is efficient for typical counting tasks, but it has some limitations to keep in mind:
- Memory usage: Since it stores every unique element as a key, memory grows with the number of distinct items, not the total item count. For millions of unique values, consider using a more memory-efficient structure like a
defaultdict(int)with manual counting, though Counter is usually fine. - Speed: For very large datasets, Counter’s overhead is comparable to a manual dictionary loop, but it is often faster due to optimized C internals in CPython.
- Negative counts: After
subtract(), counts can be negative, which may be unexpected. You can remove non-positive counts with+(e.g.,c + Counter()) or by filtering. - Hashability: Only hashable objects can be counted. If you need to count unhashable types like lists, convert them to tuples first.
One common misconception: Counter does not automatically sort by count. It maintains insertion order (like a regular dict), and most_common() is the way to get sorted results.
Alternatives to Counter
Depending on your needs, you might consider other tools:
- Plain dictionary: Use
d = {}and manually increment:d[key] = d.get(key, 0) + 1. This is more verbose but gives full control. - defaultdict(int):
d = defaultdict(int); d[key] += 1is cleaner than a plain dict and slightly faster than Counter for simple counting, but lacks Counter’s extra methods. - Pandas
value_counts(): For large datasets or when you need additional data analysis, pandas offersSeries.value_counts()which returns a sorted Series of counts. - NumPy
unique(): For numerical arrays,np.unique(arr, return_counts=True)gives counts efficiently.
Choose Counter when you need the convenience of methods like most_common() or arithmetic operations. For simple counting in a tight loop, defaultdict(int) might be slightly faster.
Frequently Asked Questions
Is Counter a dictionary? Yes, Counter is a subclass of dict. It inherits all dict methods and behaviors, but adds counting-specific methods. You can use it anywhere a dict is expected.
How do I get the count of a specific element? Use counter[element]. If the element is not present, it returns 0 instead of raising a KeyError. For example, c = Counter('abc'); c['z'] returns 0.
Can I count items in a list of lists? No, because lists are unhashable. Convert each inner list to a tuple: Counter(tuple(lst) for lst in list_of_lists).
How do I remove elements with zero or negative counts? Use the unary plus operator: c = +c will keep only positive counts. Alternatively, you can filter with a dict comprehension: {k: v for k, v in c.items() if v > 0}.
What is the difference between update() and add()? Counter does not have an add() method. Use update() to add counts from another iterable or mapping. For adding two counters, use the + operator: c1 + c2.
Is Counter available in Python 2? Counter was introduced in Python 2.7. In Python 3, it is fully supported. If you are using an older version, you would need to implement counting manually.
Related
- Excel Template for Tracking Monthly Expenses
- Excel Template for Timesheet Job Tracking
- Excel Template for Snowball Debt Payoff
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 Change the Default Date Format in Google SheetsTo change the default date format in Google Sheets, open the spreadsheet and choose File > Settings, then…
- Data Validation Interview Questions and Strong AnswersData validation interview questions test whether you can define rules for acceptable data, detect records that break those…
- Excel: Freeze the Top Row and First ColumnYes. In Excel for Microsoft 365 on Windows, select cell B2, then choose View > Freeze Panes >…
- Vendor Quotation Comparison Template in ExcelTo make a vendor quotation comparison template in Excel, list suppliers in columns B through D and put…
- Merge Cells in Google Sheets: Steps and Data TipsTo merge cells in Google Sheets in a web browser, select the cells, then choose Format > Merge…
- How to Sum Just Subtotals in Excel Without Double-CountingWhen your subtotal rows contain Excel SUBTOTAL formulas, place an outer SUBTOTAL over the detail-and-subtotal range: it skips…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.