A Counter in Python is a dictionary subclass from the collections module that counts hashable items: Counter("mississippi") returns the number of times each letter appears. Pass it any iterable, then use most_common() to rank the results.
from collections import Counter
letters = Counter("mississippi")
print(letters)
print(letters.most_common(2))
Example output:
Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
[('i', 4), ('s', 4)]
How to create a Counter
The Python documentation lists four ways to build one:
from collections import Counter
c = Counter() # a new, empty counter
c = Counter("gallahad") # from an iterable
c = Counter({"red": 4, "blue": 2}) # from a mapping
c = Counter(cats=4, dogs=8) # from keyword arguments
When you pass an iterable, each element is counted once per appearance. When you pass a mapping, the values are used as the starting counts. Elements must be hashable, so strings, numbers and tuples work, but lists do not. Counter has existed since Python 3.1.
How to count words in a list or a sentence
Counting words is the most common use. Split the text first, because a Counter given a string counts characters, not words. See how str.split() works if the split step is unfamiliar.
from collections import Counter
text = "the cat and the hat and the bat"
words = Counter(text.split())
print(words)
print(words.most_common(2))
print(words["the"])
print(words["dog"])
Example output:
Counter({'the': 3, 'and': 2, 'cat': 1, 'hat': 1, 'bat': 1})
[('the', 3), ('and', 2)]
3
0
The last line shows the main difference from a plain dictionary. A Counter returns a count of zero for a missing item instead of raising KeyError. The lookup does not add the key, so "dog" is still not in the counter afterwards.
Counter vs a plain dict and defaultdict
Without Counter, you have to handle the first occurrence of each key yourself. A plain dictionary needs get() or an if check:
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
A defaultdict(int) removes the check. The Python docs note that setting default_factory to int makes it useful for counting, because a missing key gets a default of zero:
from collections import defaultdict
counts = defaultdict(int)
for word in text.split():
counts[word] += 1
Counter does the whole loop in one call, and it also gives you sorting by frequency, arithmetic between counters and comparisons. Because it is a dict subclass, everything you know about Python dictionaries still applies: keys(), values(), items(), del and iteration all work. Since Python 3.7 it also remembers insertion order, which is why equal counts print in the order the items first appeared.
The dictionary documentation explains the missing-key behaviour. If a dict subclass defines __missing__(), then d[key] calls it when the key is absent. Counter uses this to return 0. Only d[key] calls it: get() and in do not, which is why a missing key is never inserted by a lookup.
How to update a Counter
Use update() to add more counts. Unlike dict.update(), it adds to the existing counts instead of replacing them. It also expects a sequence of elements, not a sequence of (key, value) pairs.
c = Counter(a=3, b=1)
c.update("aab")
print(c)
c["a"] += 1 # increment one key directly
c["z"] = 0 # a zero entry stays in the counter
del c["z"] # del removes it for real
print(c)
Example output:
Counter({'a': 5, 'b': 2})
Counter({'a': 6, 'b': 2})
Setting a count to zero does not remove the key. Only del does.
Subtract counts and use negative values
subtract() works like update() in reverse. Counts can drop to zero or go negative, and both are kept. This example comes from the Python documentation:
c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
print(c)
Example output:
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
That is useful for tracking stock levels or checking whether one multiset of items covers another. If you want only the positive results, use the - operator instead, described below.
Get the total, the elements and the least common items
total() adds up all the counts. It was added in Python 3.10. On earlier versions use sum(c.values()).
c = Counter(a=10, b=5, c=0)
print(c.total()) # 15
print(len(c)) # 3, the number of distinct keys
Note the difference: len(c) counts distinct keys, and total() counts every occurrence.
elements() is the opposite of counting. It returns an iterator that repeats each item as many times as its count. Items with a count below one are ignored, and it needs integer counts:
c = Counter(a=4, b=2, c=0, d=-2)
print(sorted(c.elements()))
Example output:
['a', 'a', 'a', 'a', 'b', 'b']
most_common() with no argument returns every item, from the most common to the least. The docs give a slice for the opposite end, the n least common items:
c = Counter("abracadabra")
print(c.most_common(3)) # [('a', 5), ('b', 2), ('r', 2)]
print(c.most_common()[:-3:-1]) # the 2 least common
Items with equal counts come out in the order they were first encountered.
Add, subtract and compare Counters
Counters behave like multisets (bags). The arithmetic operators combine them by key, and the results keep only counts above zero:
c = Counter(a=3, b=1)
d = Counter(a=1, b=2)
print(c + d) # c[x] + d[x]
print(c - d) # c[x] - d[x], positive counts only
print(c & d) # intersection: min(c[x], d[x])
print(c | d) # union: max(c[x], d[x])
Example output:
Counter({'a': 4, 'b': 3})
Counter({'a': 2})
Counter({'a': 1, 'b': 1})
Counter({'a': 3, 'b': 2})
Python 3.15 adds ^, the symmetric difference, which returns max(c[x], d[x]) - min(c[x], d[x]). Do not use it if you need to support earlier versions.
Unary + removes zero and negative counts, and unary - flips the sign and keeps what was negative:
c = Counter(a=2, b=-4)
print(+c) # Counter({'a': 2})
print(-c) # Counter({'b': 4})
Counters also support ==, !=, <, <=, > and >=, added in Python 3.10. Missing items count as zero, so Counter(a=1) == Counter(a=1, b=0) is true. Before 3.10 those two were considered different. A practical use of <= is an anagram or "can I build this word" check: Counter("tea") <= Counter("ate") is true when every letter of the left side is available on the right.
Common mistakes with Counter
- Passing a string when you want words.
Counter("the cat")counts characters, including the space. Call.split()first. - Expecting
update()to replace. It adds. To overwrite one count, assign it:c["a"] = 1. - Using
Counter.fromkeys(). The docs say it is not implemented forCounterand raises an error. - Counting unhashable items. A list of lists raises
TypeError: unhashable type: 'list'. Convert each inner list to a tuple first. - Trusting
most_common(1)on a tie. It returns whichever tied item appeared first. If a tie matters, checkmost_common()for equal counts. - Using the operators on counters with negative values and expecting them to be kept.
+,-,&and|drop results of zero or below. Useupdate()orsubtract()to keep them.
Count items that are not strings
Any hashable value works. A common pattern is counting a field across a list of records, such as the file extensions in a folder:
from collections import Counter
from pathlib import Path
extensions = Counter(path.suffix.lower() for path in Path(".").iterdir() if path.is_file())
print(extensions.most_common(3))
Example output, which depends on the folder:
[('.py', 12), ('.txt', 4), ('.md', 2)]
A generator expression like this keeps memory use low, since the counter only stores one entry per distinct item, not one per input item.
Convert a Counter to a dict or a list
Because it is already a dictionary, dict(c) gives a plain dictionary and c.items() gives the (item, count) pairs. To go the other way, from a list of pairs, use Counter(dict(list_of_pairs)), not Counter(list_of_pairs), which would count the tuples themselves. list(c) and set(c) return the distinct items, and c.clear() resets everything.
Frequently asked questions
- Is Counter a dictionary in Python?
- Yes. collections.Counter is a subclass of dict, so it has the usual dictionary methods such as keys(), values() and items(). The difference is that looking up a missing key returns 0 instead of raising KeyError, and it adds counting helpers such as most_common() and update().
- How do I get the most frequent item with Counter?
- Call most_common(1) on the counter. It returns a list with one (item, count) tuple, for example [('a', 5)]. Take the first element of that list to get the tuple. If several items tie, the one encountered first in the input comes first.
- Does Counter ignore items with a zero or negative count?
- Not always. Indexing, items() and most_common() show zero and negative counts. The multiset operators (+, -, & and |), unary + and elements() drop or ignore counts of zero and below. Use +counter to get a copy with only positive counts.
- Which Python version added Counter.total()?
- Counter.total() was added in Python 3.10. On older versions use sum(counter.values()), which gives the same result.