Counter
A lot of interview problems ask how many times each item shows up. Anagram checks, frequency problems and "find the most common element" problems all need a count of every item in a collection.
You could build that count yourself with a plain dict and a loop. But Python’s collections module already has a tool made for this called Counter. It’s a kind of dict. Everything you already know about dicts still works on it. It also adds a few methods that make counting code shorter to write.
Here’s the syntax if that’s all you need:
from collections import Counter
counts = Counter(["red", "blue", "red", "green", "red"])
print(counts["red"]) # 3, the count for one item
print(counts["purple"]) # 0, missing items don't raise
print(counts.most_common(2)) # the 2 most common, highest first
counts["blue"] += 1 # update a count
for item, count in counts.items():
print(item, count) # loop over every countCounting occurrences of each element
O(n)If you pass a list (or anything else you can loop over) to Counter(), it counts every element for you. Here it is on a list:
from collections import Counter
votes = ["red", "blue", "red", "green", "blue", "red"]
counts = Counter(votes)
print(counts)You can loop over the characters in a string too. That means the same call counts letters:
from collections import Counter
letters = Counter("mississippi")
print(letters)Note
Try not to rely on the order these print in. In standard Python, a printed Counter shows the highest counts first. That’s only how it displays, though. Use most_common() if your code needs a specific order. We cover that next.
most_common() and how ties break
O(n log n)most_common() gives you the counts from highest to lowest as a list of tuples. That list is usually easier to work with than the Counter itself. Pass in a number if you only want the top few:
from collections import Counter
words = ["cat", "dog", "cat", "dog", "bird"]
counts = Counter(words)
print(counts.most_common())
print(counts.most_common(2))Note
How ties break: "cat" and "dog" both show up twice. "cat" comes first in the result because it was counted first. Ties go to whichever item showed up first, not to whichever comes first alphabetically. Keep this in mind when an interviewer asks for "the most common element" and more than one answer is valid.
Counter vs a plain dict
O(1)The biggest difference shows up when you look up a key that was never counted. A Counter returns 0 instead of raising an error.
from collections import Counter
counts = Counter(["a", "b", "a"])
print(counts["a"])
print(counts["z"])If you do the same lookup on a plain dict, you get a KeyError:
plain = {"a": 2, "b": 1}
try:
print(plain["z"])
except KeyError as e:
print(f"KeyError: {e}")Note
This is why counts[item] += 1 works with a Counter the very first time you see item. With a plain dict, that same line raises a KeyError. You’d have to check item in d or use d.get(item, 0) first.
Counter arithmetic (+, -, &, |)
O(n + m)You can combine two counters with these operators:
+adds the counts.-subtracts them.&keeps the smaller count for each key.|keeps the larger count for each key.
Here they are on two small counters:
from collections import Counter
a = Counter(a=3, b=1, c=0)
b = Counter(a=1, b=2, c=3, d=0)
print(a + b)
print(a - b)
print(a & b)
print(a | b)Note
Watch out: All four operators quietly drop any key whose result is zero or negative. Above, c starts at 0 in a. d starts at 0 in b. Neither one shows up in the subtraction or intersection results. a - b drops b and c completely because their counts go negative. It doesn’t keep them at 0. Use a.subtract(b) instead if you need to keep zero or negative counts. It changes a in place and keeps every key.
Sorting and looping over a Counter
To sort by count with the highest first, use most_common(). For any other order, pass .items() to sorted() with a key:
from collections import Counter
counts = Counter("mississippi")
print(counts.most_common()) # by count, highest first
print(sorted(counts.items(), key=lambda kv: kv[1])) # by count, lowest first
print(sorted(counts.items())) # by key, alphabetically
print(sorted(counts, key=counts.get, reverse=True)) # just the keys, by countYou loop over a Counter the same way you loop over any dict. Loop over .items() to get each item with its count. Loop over the Counter itself to get just the items:
from collections import Counter
counts = Counter("mississippi")
for letter, count in counts.items():
print(letter, count)
for letter, count in counts.most_common():
print(letter, count) # same thing, but highest count firstConverting a Counter
A Counter is a dict. That means dict() and .items() work on it the same way they do on any dict:
from collections import Counter
counts = Counter("aabbbc")
print(dict(counts))
print(list(counts.items()))Note
dict() and .items() keep the order the keys were first added in. Here, "a" comes first because it was seen first. That’s not the same as the sorted-by-count order from most_common(). Don’t assume a converted Counter is sorted by count.
elements() does the opposite of counting. It turns the counts back into individual items. Each item is repeated as many times as its count. The items come out in the order they were first added. Any key with a zero or negative count gets skipped.
from collections import Counter
counts = Counter("aabbbc")
print(list(counts.elements()))Where Counter shows up in interviews
Try Counter before you write your own loop any time a problem asks you to "count these, then compare the counts." Two kinds of problems come up over and over:
- Anagram checks. Two strings are anagrams if
Counter(s1) == Counter(s2). You can compare two Counters with==directly. You don’t need to sort either string first. See Permutation in String for a sliding-window version of this idea. - Frequency-window problems. Some problems slide a window across a string or list. They ask whether the letter counts in the window match a target. Solutions to these almost always keep a
Counterfor the window and compare it to a targetCounter. See Minimum Window Substring and Longest Repeating Character Replacement for two versions of that pattern.