Sub topic 3
most_common, update, subtract, and Counter arithmetic
This chapter assumes you can create a Counter from an iterable and read a count from it, including the fact that a missing key reads as 0. It also assumes you are comfortable with dict methods and with Python's sorted and slicing. Here you will work through the methods and operators that change counts and compare them. The main skill is knowing which operations keep zero and negative counts and which silently drop them.
Counter as a multiset
A Counter is a dict subclass whose values are counts. You can treat it as a multiset, which is a set where each element can appear more than once. Two families of operations act on it:
- Methods such as
updateandsubtractchange the counter in place and keep every count they produce, including zero and negative values. - Operators such as
+,-,&, and|build a new counter and keep only counts greater than zero.
Most surprises with Counter come from mixing these two families, so keep the difference in mind throughout.
most_common: ranking by count
most_common(n) returns a list of (item, count) pairs, highest count first. If you leave out n or pass None, you get every item.
from collections import Counter
c = Counter("abracadabra")
print(c.most_common(3)) # [('a', 5), ('b', 2), ('r', 2)]
print(c.most_common()) # [('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]
print(c.most_common(0)) # []
print(c.most_common(99)) # same as c.most_common()
print(c.most_common()[:-3:-1]) # [('d', 1), ('c', 1)]The last line is the usual idiom for the two least common items. The slice walks the sorted list backwards from the end and stops before index -3.
Ties
When two items have the same count, most_common keeps them in the order they were first inserted into the counter. In the example above, b appears before r in the text, so b comes first. This is a documented guarantee in Python 3.7 and later, because dicts preserve insertion order.
The slice idiom reverses that order within a tie. That is why d comes before c in the last output even though c was seen first. If you need a specific tie-break rule, sort explicitly instead of relying on insertion order:
from collections import Counter
c = Counter("abracadabra")
by_count_then_letter = sorted(c.items(), key=lambda kv: (-kv[1], kv[0]))
print(by_count_then_letter) # [('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]Cost
most_common() with no argument sorts all items, so it takes time proportional to k log k for k distinct items. With a small n, Python uses a heap-based selection that costs about k log n. For "top 10 of a million distinct words", always pass n.
most_common sorts by value, so negative counts sort to the bottom. The same ordering is used when you print a counter, so print(c) shows the highest counts first.
update: adding counts
Counter.update accepts an iterable, a mapping, or keyword arguments. How the argument is read depends on its type:
- An iterable is counted item by item. Each occurrence adds 1.
- A mapping is read as
item: countpairs. Each count is added to the existing count. - Keyword arguments work like a mapping with string keys.
from collections import Counter
inv = Counter(apples=3, pears=1)
inv.update(["apples", "kiwis"]) # iterable: each item counts once
inv.update({"pears": 5}) # mapping: counts are added
inv.update(plums=2) # keyword arguments work too
print(inv) # Counter({'pears': 6, 'apples': 4, 'plums': 2, 'kiwis': 1})The constructor Counter(source) behaves like creating an empty counter and calling update(source), so both accept the same kinds of input.
from collections import Counter
d = {"a": 1}
d.update({"a": 5})
print(d) # {'a': 5}
c = Counter(a=1)
c.update({"a": 5})
print(c) # Counter({'a': 6})update keeps whatever counts result, so adding a negative count can leave a zero or negative entry in the counter. The method returns None, as other in-place container methods do, so you cannot chain calls.
subtract: removing counts without clamping
subtract takes the same kinds of argument as update but removes counts. It does not stop at zero.
from collections import Counter
stock = Counter(widgets=5, gears=2)
stock.subtract(Counter(widgets=2, gears=4, bolts=1))
print(stock) # Counter({'widgets': 3, 'bolts': -1, 'gears': -2})
stock.subtract(["widgets"]) # an iterable subtracts 1 per occurrence
print(stock["widgets"]) # 2The negative counts here are real data. Here they record that you owe 2 gears and 1 bolt. This is the main reason to prefer subtract over the - operator when you want to keep track of shortfalls.
Two unary operators let you split a counter into its positive and negative parts:
print(+stock) # Counter({'widgets': 2})
print(-stock) # Counter({'gears': 2, 'bolts': 1})+stock keeps only the positive counts. -stock negates every count and keeps only the results that are positive, so it returns the shortfalls as positive numbers. Both were added in Python 3.3.
elements and total
elements() is the inverse of counting. It returns an iterator that repeats each item as many times as its count, in the order items were first inserted. Items with a count below 1 are skipped.
total() returns the sum of all counts. It was added in Python 3.10.
from collections import Counter
c = Counter(a=2, b=1, c=0, d=-1)
print(list(c.elements())) # ['a', 'a', 'b']
print(c.total()) # 2
print(sum(v for v in c.values() if v > 0)) # 3total() is a plain sum of the values, so negative counts reduce it. elements() ignores them. If your counter may hold negative values and you want the number of items that elements() would produce, use the third line above.
Arithmetic operators
The four binary operators treat two counters as multisets and return a new Counter.
| Operator | Meaning | Count for each key | Column |
|---|---|---|---|
| `a + b` | Combine | `a[k] + b[k]` | |
| `a - b` | Remove | `a[k] - b[k]` | |
| `a & b` | Intersection | `min(a[k], b[k])` | |
| `a \ | b` | Union | `max(a[k], b[k])` |
In every case, keys whose result is zero or less are left out of the returned counter. Missing keys count as 0.
from collections import Counter
a = Counter(apples=3, pears=1)
b = Counter(apples=1, pears=2)
print(a + b) # Counter({'apples': 4, 'pears': 3})
print(a - b) # Counter({'apples': 2})
print(a & b) # Counter({'apples': 1, 'pears': 1})
print(a | b) # Counter({'apples': 3, 'pears': 2})Look at a - b. For pears the result is 1 - 2 = -1, which is dropped. The operator never reports a deficit. If you need the other direction, compute b - a as well. Combining both gives the absolute difference per key:
print((a - b) + (b - a)) # Counter({'apples': 2, 'pears': 1})Subtraction is not symmetric. a - b and b - a answer different questions: what a has beyond b, and what b has beyond a.
Negative inputs
The operators accept counters that already contain zero or negative counts, and they apply the same rule to the final result. A negative count in an input can cancel part of a positive one:
from collections import Counter
print(Counter(a=-1) + Counter(a=3)) # Counter({'a': 2})
print(Counter(a=-1) + Counter(b=1)) # Counter({'b': 1})In the first line, -1 + 3 = 2 is positive and is kept. In the second, a ends at -1 and is dropped.
In-place operators and cleaning up
The operators +=, -=, &=, and |= update the left counter, but they still discard non-positive results. That makes += with an empty counter a cheap way to clean a counter in place:
from collections import Counter
c = Counter(a=2, b=0, c=-3)
print(+c) # Counter({'a': 2})
print(-c) # Counter({'c': 3})
c += Counter() # removes zero and negative counts in place
print(c) # Counter({'a': 2})Which operations keep zero and negative counts
This is the rule to memorize. The diagram groups the operations by what they do with non-positive results.
| Operation | Changes the counter in place | Keeps zero and negative counts | Column |
|---|---|---|---|
| `update(x)` | Yes | Yes | |
| `subtract(x)` | Yes | Yes | |
| `a + b`, `a - b`, `a & b`, `a \ | b` | No, returns a new counter | No |
| `a += b`, `a -= b`, `a &= b`, `a \ | = b` | Yes | No |
| `+a`, `-a` | No, returns a new counter | No |
A common bug follows from this table. If you use -= to apply a stream of withdrawals, any key that falls below zero is deleted instead of recorded. Use subtract when you need the negative balance, and use -= when you want the counter to hold only what is still available.
Comparing counters
Python 3.10 added rich comparisons to Counter. They treat a missing key as a count of 0:
a == bis true when every key has the same count in both, soCounter(a=0) == Counter()is true.a <= bis true when every count inais at most the matching count inb. This is the multiset "is a subset of" test.a < bis a strict subset.>=and>work in the other direction.
from collections import Counter
need = Counter("hello")
have = Counter("helloworld")
print(need <= have) # True: every letter in "hello" is available
print(have <= need) # False: "helloworld" has letters that "hello" lacks
print(not (need - have)) # True: nothing is missing
print(Counter(a=1) < Counter(a=1, b=1)) # True
print(Counter(a=0) == Counter()) # True on 3.10+, False beforeOn Python 3.9 and earlier, the order operators are not defined for counters and raise TypeError, and == compares like a dict, so zero counts matter. The not (need - have) form works on every version, because need - have is empty exactly when have covers need.
Worked example: a recipe against a pantry
This example uses most of the chapter. The - operator answers "what do I still need to buy?" and subtract applies the cooking to the pantry and keeps the overdraw visible.
from collections import Counter
def shortfall(need, have):
"""Return what is still missing, as a Counter of positive counts."""
return need - have
recipe = Counter(flour=3, eggs=2, sugar=1)
pantry = Counter(flour=1, eggs=6)
missing = shortfall(recipe, pantry)
print(missing) # Counter({'flour': 2, 'sugar': 1})
print(missing.most_common(1)) # [('flour', 2)]
pantry.subtract(recipe) # cook anyway
print(pantry) # Counter({'eggs': 4, 'sugar': -1, 'flour': -2})
print(-pantry) # Counter({'flour': 2, 'sugar': 1})After subtract, the pantry holds the same shortfall that missing reported, now stored as negative counts. -pantry converts it back into positive numbers.
Common errors
- Expecting
updateto replace values. It adds them. To replace a count, assign it withc[key] = value. - Using
-or-=and then wondering where the negative counts went. Operators drop them. Usesubtractto keep them. - Passing a plain string to
updateorCounterwhen you meant a single item. A string is an iterable of characters, soCounter("apple")counts letters. UseCounter(["apple"])to count one item. - Reading
len(c)as a total. It counts keys, including zero-count ones. - Calling
total()or using comparison operators on Python 3.9 or earlier. Checkpython --versionif you get anAttributeErroror aTypeError. - Relying on tie order from the slice idiom for least common items. The slice reverses tie order, so sort explicitly when ties matter.
- Using
elements()on a huge count. It produces one item per unit of count, soCounter(x=10**9).elements()will run for a very long time if you consume it.
Exercise
Starting from c = Counter(a=2, b=1), you run c.subtract(Counter(a=3)). What are the values of c, +c, and c - Counter(b=5)?
Show answer
c is Counter({'b': 1, 'a': -1}), because subtract keeps the negative count for a. +c is Counter({'b': 1}), because unary plus drops non-positive counts. c - Counter(b=5) is an empty Counter(): a is -1 and b is 1 - 5 = -4, and both results are dropped.
Exercise
Why does Counter(a=1) | Counter(a=3, b=-2) not contain the key b, and what is the result?
Show answer
The | operator takes the maximum count for each key, and for b that is max(0, -2) = 0 because a missing key counts as 0. Operators keep only counts above zero, so b is dropped. The result is Counter({'a': 3}).