Sub topic 3
most_common, update, subtract, and Counter arithmetic
This chapter assumes you can create a Counter and read counts from it, as covered in the previous chapter. It also assumes you know how dict.update() behaves. Here you will rank counts, change them in place, and combine whole counters.
Ranking with most_common
most_common(n) returns a list of (item, count) pairs, highest count first. Without an argument it returns every item.
from collections import Counter
c = Counter("abracadabra")
print(c.most_common(3)) # [('a', 5), ('b', 2), ('r', 2)]
print(c.most_common()[-1]) # ('d', 1)
print(c.total()) # 11Items with equal counts keep the order in which they were first seen. Here b comes before r because b appeared first in the string. The total() method needs Python 3.10 or later. It sums all the counts.
To get the least common items, slice the full list from the end: c.most_common()[:-3:-1] returns the two lowest.
update adds, it does not replace
On a plain dict, update() overwrites values. On a Counter, update() adds to them. It accepts either an iterable of items or a mapping of counts.
from collections import Counter
c = Counter(a=2, b=1)
c.update(["a", "b", "b"]) # an iterable: each item counts once
print(c) # Counter({'a': 3, 'b': 3})
c.update({"a": 10}) # a mapping: its values are added
print(c) # Counter({'a': 13, 'b': 3})A common error is assuming that c.update({"a": 10}) sets a to 10. It makes a 10 higher than before.
subtract keeps zero and negative counts
subtract() is the in-place opposite of update(). It does not remove anything, so counts can reach zero or go below it.
from collections import Counter
stock = Counter(apples=5, pears=2)
stock.subtract(Counter(apples=2, pears=4, kiwis=1))
print(stock) # Counter({'apples': 3, 'kiwis': -1, 'pears': -2})
print(+stock) # Counter({'apples': 3})Negative counts are useful when you track a shortfall, such as an order that exceeds stock. The unary + operator returns a new counter that keeps only the positive counts. Unary - keeps only the negative counts and flips their sign.
The printed order follows most_common(), which is why kiwis appears before pears.
elements expands counts back into items
elements() is the reverse of counting. It yields each item as many times as its count. Items with a count below 1 are skipped.
from collections import Counter
c = Counter(a=2, b=1, c=0, d=-1)
print(sorted(c.elements())) # ['a', 'a', 'b']The method returns an iterator, so wrap it in list() or sorted() if you need a list.
Arithmetic on whole counters
The operators +, -, &, and | combine two counters and return a new one. Each operator works item by item.
| Operator | Per-item rule | Meaning | Column |
|---|---|---|---|
| `a + b` | add counts | combine tallies | |
| `a - b` | subtract counts | what `a` has beyond `b` | |
| `a & b` | minimum of counts | what both have in common | |
| `a \ | b` | maximum of counts | the larger tally for each item |
These operators share one rule: a result with a count of zero or below is dropped. That differs from subtract(), which keeps those counts.
from collections import Counter
a = Counter(x=1, y=4)
b = Counter(x=3, y=1)
print(a - b) # Counter({'y': 3})
a.subtract(b)
print(a) # Counter({'y': 3, 'x': -2})The expression a - b loses x because 1 - 3 is negative. The method a.subtract(b) keeps x with a count of -2.
The in-place forms +=, -=, &=, and |= also exist. They drop non-positive counts in the same way. Use subtract() when you want to keep them.
A worked example: comparing two inventories
Suppose you want to know what to restock. Compare what a shop has with what it needs.
from collections import Counter
have = Counter(bolts=40, nuts=25, washers=10)
need = Counter(bolts=30, nuts=30, washers=10, screws=5)
missing = need - have
spare = have - need
print(missing) # Counter({'screws': 5, 'nuts': 5})
print(spare) # Counter({'bolts': 10})Washers appear in neither result, because 10 - 10 is zero and zero counts are dropped. That makes need - have convenient for finding only the shortfalls.
Common errors
- Treating
update()as assignment. It adds to existing counts. To set a count, writec["a"] = 10. - Expecting
-to produce negatives. The operator drops them. Usesubtract()if you need them. - Calling
elements()on negative counts. Those items are silently skipped. - Using non-integer counts with
most_common(). Counts can be any value that supports comparison, butelements()andtotal()assume whole numbers or numbers that can be summed. Stick to integers unless you have a reason.
Exercise
Given inventory = Counter(a=3, b=1) and sold = Counter(a=1, b=4), write code that prints the items that are now oversold, meaning sold exceeds inventory, along with how far over they are. What does it print?
Show answer
Use the minus operator in the other direction: print(sold - inventory). Only b has more sold than in stock (4 - 1 = 3), and a is dropped because 1 - 3 is negative. The output is Counter({'b': 3}).