Counter
A dict subclass that counts hashable items in O(n). Use it for frequency problems: anagrams, top-k frequent, "can I build X from Y" (multiset subtraction). Missing keys return 0 instead of raising KeyError.
Syntax
from collections import Counter
c = Counter("banana") # -> Counter({'a': 3, 'n': 2, 'b': 1}), O(n)
c["a"] # -> 3
c["z"] # -> 0, no KeyError and no insertion
most_common
from collections import Counter
c = Counter([1, 1, 1, 2, 2, 3])
c.most_common(2) # -> [(1, 3), (2, 2)], O(n log k)
c.most_common() # all, sorted by count desc
[x for x, _ in c.most_common(2)] # top-k frequent elements -> [1, 2]
c.most_common()[-1] # -> (3, 1), least common
Anagram check
from collections import Counter
Counter("listen") == Counter("silent") # -> True, O(n)
# 3.10+: == treats missing and zero counts as equal
Arithmetic
from collections import Counter
a, b = Counter("aab"), Counter("abc")
a + b # -> Counter({'a': 3, 'b': 2, 'c': 1})
a - b # -> Counter({'a': 1}), drops counts <= 0
a & b # -> Counter({'a': 1, 'b': 1}), min of each
a | b # -> Counter({'a': 2, 'b': 1, 'c': 1}), max of each
Can I build ransomNote from magazine? (LeetCode 383)
from collections import Counter
note, mag = "aab", "baa"
not (Counter(note) - Counter(mag)) # -> True, nothing missing
Counter(note) <= Counter(mag) # -> True, subset test (3.10+)
update / subtract
from collections import Counter
c = Counter()
c.update("aab") # add counts -> {'a': 2, 'b': 1}
c.subtract("ab") # keeps zeros/negatives -> {'a': 1, 'b': 0}
c["a"] -= 1 # sliding-window style decrement
if c["a"] == 0:
del c["a"] # delete so len(c) == number of distinct items
elements and total
from collections import Counter
c = Counter(a=2, b=1)
list(c.elements()) # -> ['a', 'a', 'b']
c.total() # -> 3, sum of counts (3.10+)
len(c) # -> 2, distinct keys