Sub topic 2
Counting things with Counter
This chapter assumes you can write loops and functions, use dict and list (key lookup, append), and know why a list cannot be a dict key. It also assumes you know how to import from the standard library. It covers how to create a Counter, how to read and change its counts, and the edge cases that surprise people. The next chapter covers most_common, update, subtract, and arithmetic in more depth.
The problem Counter solves
Counting how often things occur is one of the most common small tasks in programming. With a plain dict you have to handle the first time you see each item:
counts = {}
for ch in "banana":
counts[ch] = counts.get(ch, 0) + 1
print(counts) # {'b': 1, 'a': 3, 'n': 2}The get(ch, 0) supplies a starting value for new keys. It works, but you have to write that pattern every time, and a typo in it fails silently. Counter packages the pattern as a dict subclass:
from collections import Counter
counts = Counter("banana")
print(counts) # Counter({'a': 3, 'n': 2, 'b': 1})A Counter is a dict whose keys are the items you count and whose values are the counts. Because it subclasses dict, everything you know about dicts still applies: len, in, .items(), .keys(), .values(), iteration, and insertion order (kept since Python 3.7).
The printed form of a Counter lists items from the highest count to the lowest. That is a display choice. The iteration order is still insertion order, as the next section shows.
Creating a Counter
You can build a Counter in four ways. All of them go through the same constructor, which looks at what you passed.
| Call | What it does | Result |
|---|---|---|
| `Counter()` | Starts empty | `Counter()` |
| `Counter(["a", "b", "a"])` | Counts each element of an iterable | `Counter({'a': 2, 'b': 1})` |
| `Counter({"red": 4, "blue": 2})` | Treats the mapping's values as counts | `Counter({'red': 4, 'blue': 2})` |
| `Counter(cats=4, dogs=8)` | Treats keyword arguments as counts | `Counter({'dogs': 8, 'cats': 4})` |
from collections import Counter
empty = Counter()
from_list = Counter(["a", "b", "a"])
from_mapping = Counter({"red": 4, "blue": 2})
from_keywords = Counter(cats=4, dogs=8)
print(empty) # Counter()
print(from_list) # Counter({'a': 2, 'b': 1})
print(from_mapping) # Counter({'red': 4, 'blue': 2})
print(from_keywords) # Counter({'dogs': 8, 'cats': 4})The second and third forms look alike but behave differently, and mixing them up is the most common beginner error with Counter. The diagram shows how the constructor decides.
Counting a mapping versus counting its contents
When you pass a dict, Counter does not count the dict's keys. It copies the values as counts. If you want to count the values themselves, pass .values(), which is an ordinary iterable:
from collections import Counter
scores = {"ana": 2, "ben": 2, "cy": 5}
print(Counter(scores)) # Counter({'cy': 5, 'ana': 2, 'ben': 2})
print(Counter(scores.values())) # Counter({2: 2, 5: 1})The first line says "ana has 2, ben has 2, cy has 5". The second says "the value 2 appears twice, the value 5 appears once".
A string is an iterable of characters, so Counter("banana") counts letters. To count words, split first:
from collections import Counter
print(Counter("the cat the".split())) # Counter({'the': 2, 'cat': 1})Passing a plain string without .split() is a frequent mistake, and the result looks plausible, so it is easy to miss.
Reading counts
Reading a count uses normal dict syntax, with one difference: a missing key does not raise KeyError. It reads as zero.
from collections import Counter
c = Counter("banana")
print(c["a"]) # 3
print(c["z"]) # 0
print("z" in c) # False
print(len(c)) # 3
print(list(c)) # ['b', 'a', 'n']The lookup c["z"] returns 0 but does not store z. The check "z" in c is still False afterward, and len(c) is unchanged. This is different from defaultdict, which inserts the key on lookup (a later chapter covers that contrast). Internally, Counter defines __missing__, which dict calls when [] fails to find a key, and Counter.__missing__ returns 0 without storing anything.
The list(c) line shows insertion order: b was seen first, then a, then n. It does not show count order.
get() does not use the zero default
__missing__ runs only for the [] operator. The get method bypasses it, so it behaves as it does on any dict:
from collections import Counter
c = Counter("banana")
print(c.get("z")) # None
print(c.get("z", 0)) # 0
print(c["z"]) # 0If your code relies on c.get("z") giving a number, it will get None and may fail later in arithmetic. Prefer indexing when you want the zero default.
Totals
To find the total number of items counted, sum the values. Python 3.10 added Counter.total() for this:
from collections import Counter
c = Counter("banana")
print(sum(c.values())) # 6
print(c.total()) # 6 (Python 3.10 and later)Note that len(c) is the number of distinct items (3 here), not the number of items counted (6).
Changing counts by hand
Because a missing key reads as 0, the update pattern needs no setup:
from collections import Counter
stock = Counter()
stock["apples"] += 3
stock["pears"] += 1
stock["apples"] += 2
print(stock) # Counter({'apples': 5, 'pears': 1})The first stock["apples"] += 3 reads 0, adds 3, and stores 3. After that the key exists. You can also assign a count directly, as in stock["plums"] = 10.
Zero and negative counts stay in the Counter
A count that reaches zero is not removed automatically. Counts can also go negative:
from collections import Counter
inventory = Counter(apples=2)
inventory["apples"] -= 2
print(inventory) # Counter({'apples': 0})
print("apples" in inventory) # True
print(len(inventory)) # 1
inventory["apples"] -= 1
print(inventory) # Counter({'apples': -1})This surprises people who treat in as "has at least one". For a Counter, in means "has an entry", and an entry can hold 0 or a negative number. If you need "present with a positive count", test the value: if c["apples"] > 0.
To remove an entry, use del. Unlike a plain dict, del on a missing key does nothing instead of raising KeyError:
from collections import Counter
inventory = Counter(apples=0, pears=3)
del inventory["apples"]
del inventory["plums"] # no error, even though plums is not there
print(inventory) # Counter({'pears': 3})To drop every zero or negative entry at once, apply the unary plus operator, which returns a new Counter with only positive counts:
from collections import Counter
c = Counter(a=0, b=3, c=-1)
print(+c) # Counter({'b': 3})The next chapter explains this together with the other operators.
What you can count
Dict keys must be hashable, so Counter can only count hashable items. Strings, numbers, tuples of hashables, and frozenset all work. Lists, sets, and dicts do not:
from collections import Counter
try:
Counter([[1, 2], [3, 4], [1, 2]])
except TypeError as e:
print(e) # unhashable type: 'list'
pairs = [[1, 2], [3, 4], [1, 2]]
print(Counter(tuple(p) for p in pairs)) # Counter({(1, 2): 2, (3, 4): 1})The fix is to convert each unhashable item into a hashable equivalent, such as a tuple for a list or a frozenset for a set.
Counting a derived value
You often want to count a property of each item rather than the item itself. Pass a generator expression that computes the property:
from collections import Counter
words = ["apple", "fig", "kiwi", "plum", "pear"]
print(Counter(len(w) for w in words)) # Counter({4: 3, 5: 1, 3: 1})
print(Counter(w[0] for w in words)) # Counter({'p': 2, 'a': 1, 'f': 1, 'k': 1})Here the first line counts word lengths. The second counts first letters.
Keys that compare equal are the same key
Counter follows dict rules for equality. Values that are equal and hash equally share one entry. The key that stays is the first one inserted:
from collections import Counter
print(Counter([1, 1.0, True])) # Counter({1: 3})
print(Counter([1.0, 1, True])) # Counter({1.0: 3})This matters when you count mixed numbers and booleans, for example values read from loosely typed data. If the distinction between True and 1 matters to you, convert the items first.
Iterators are consumed
If you pass an iterator or generator, Counter reads it to the end. A second pass over the same iterator sees nothing:
from collections import Counter
it = iter("banana")
first = Counter(it)
second = Counter(it)
print(first) # Counter({'a': 3, 'n': 2, 'b': 1})
print(second) # Counter()If you need to count the same data twice, keep it in a list or create a new iterator.
A first look at most_common
The most frequent items are usually what you want from a count. most_common(n) returns a list of (item, count) pairs, highest first. Called with no argument, it returns every item.
from collections import Counter
words = "the cat and the hat and the bat".split()
counts = Counter(words)
print(counts.most_common(2)) # [('the', 3), ('and', 2)]
print(counts["dog"]) # 0, and 'dog' is not added to countsWhen two items have the same count, they keep the order in which they were first inserted, because the sort is stable. In the text above, cat, hat, and bat each appear once, so counts.most_common() lists them in that order after the and and. The next chapter looks at most_common more closely.
Worked example: word frequencies in a text
This script lowercases a text, extracts words with a regular expression, and reports the most common words along with a total.
import re
from collections import Counter
text = "The cat sat on the mat. The dog sat on the log. The end."
words = re.findall(r"[a-z']+", text.lower())
counts = Counter(words)
print(f"{counts.total()} words, {len(counts)} distinct")
for word, n in counts.most_common(3):
print(f"{word:<5} {n}")Output:
14 words, 8 distinct
the 5
sat 2
on 2Step by step:
text.lower()makesTheandthethe same word. Without it they would be separate keys.re.findall(r"[a-z']+", ...)pulls out runs of letters and apostrophes, so the punctuation (the periods) is dropped.Counter(words)tallies the list in one pass.most_common(3)returns the top three.satcomes beforeonbecause both have count 2 andsatwas seen first.
The total() call needs Python 3.10 or later. On older versions use sum(counts.values()).
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Counts are for letters, not words | Passed a string instead of a list of words | Use `text.split()` or a regular expression |
| Counts look copied rather than tallied | Passed a dict, so its values were taken as counts | Pass `d.values()` or `d.keys()` to count those |
| `TypeError: unhashable type` | An item is a list, set, or dict | Convert each item to a tuple or `frozenset` |
| `c.get(x)` returns `None` | `get` does not use the zero default | Use `c[x]` or `c.get(x, 0)` |
| `x in c` is true but the count is 0 | Zero and negative entries stay in the Counter | Test `c[x] > 0` or remove entries with `del` |
| A second `Counter(it)` is empty | The iterator was already consumed | Reuse a list, or make a fresh iterator |
| `len(c)` is smaller than expected | `len` is the number of distinct keys | Use `sum(c.values())` or `c.total()` for the total |
Summary of behavior to remember
Counteris adictsubclass for tallying hashable items.Counter(iterable)adds 1 per element.Counter(mapping)andCounter(name=n)use the given numbers as counts.- Indexing a missing key returns 0 and does not insert it.
getreturnsNoneinstead. - Counts can reach 0 or go negative without the key being removed.
delremoves a key and ignores missing ones. - Equal keys such as
1,1.0, andTrueshare one entry.
Exercise
You run Counter({"a": 3, "b": 1}) and expect it to count the two keys, giving a: 1 and b: 1. What do you actually get, and how would you count the keys instead?
Show answer
You get Counter({'a': 3, 'b': 1}), because a mapping argument supplies the counts directly. To count the keys as items, pass an iterable of them, for example Counter(d.keys()) or Counter(list(d)), which gives Counter({'a': 1, 'b': 1}).
Exercise
Given c = Counter(apples=1), what are the values of c["pears"], c.get("pears"), "pears" in c, and len(c) after those three lookups?
Show answer
c["pears"] is 0, c.get("pears") is None, "pears" in c is False, and len(c) is 1. None of the lookups inserts a key.
Exercise
Write code that counts how many words in ["Tea", "tea", "Coffee", "TEA", "coffee"] appear, ignoring case, and then prints the total number of words counted and the number of distinct words.
Show answer
from collections import Counter counts = Counter(w.lower() for w in ["Tea", "tea", "Coffee", "TEA", "coffee"]) print(counts) # Counter({'tea': 3, 'coffee': 2}) print(sum(counts.values())) # 5 (counts.total() on Python 3.10+) print(len(counts)) # 2
Exercise
After c = Counter(x=1) and c["x"] -= 1, does "x" in c return True or False, and how do you make the Counter empty again?
Show answer
It returns True, because the count 0 is still stored as an entry. Remove it with del c["x"], or build a new Counter without zero entries with +c.