The Python Journey

Counting with Counter

Counting with Counter

Page Contents

Overview

Tallying how many times each item appears in an input pops up constantly in Advent of Code — counting character frequencies, crate IDs, lanternfish timers, or packet types.

Without Counter, you might write a manual dictionary loop:

counts: dict[int, int] = {}
for item_id in ids:
    counts[item_id] = counts.get(item_id, 0) + 1

Python’s collections.Counter does all of that in a single line:

from collections import Counter

counts = Counter(ids)

Creating a Counter

Counter accepts any iterable — a list, a str, a tuple, or even a lazy iterator like map(int, lines) (so you don’t need to build an intermediate list first):

from collections import Counter

print(Counter([57, 57, 43, 76, 57, 43]))
# Counter({57: 3, 43: 2, 76: 1})

print(Counter("abracadabra"))
# Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})

Each unique item becomes a key, and its value is the integer count of how many times it appeared.

Dictionary-Like Behaviour and Missing Keys

Counter is a subclass of dict, so .keys(), .values(), .items(), and in all work just as you’d expect.

There is one very handy difference compared to a regular dictionary: looking up a missing key returns 0 instead of raising KeyError, and does not insert that key into the Counter:

counts = Counter([57, 57, 43])

print(counts[57])   # 2
print(counts[999])  # 0 (no KeyError!)
print(999 in counts)  # False — 999 was NOT added to counts

Contrast that with defaultdict(int), where accessing d[999] quietly inserts 999: 0 into the dictionary!

Finding the Most (and Least) Common Items

Counter includes .most_common(n), which returns a list of (item, count) tuples ordered from highest count to lowest:

  • Top n items: pass n, e.g. counts.most_common(3).
  • All items in count order: call counts.most_common() with no argument.
  • Bottom n (least common) items: combine counts.most_common() with Indexing and Slicing from the end ([-n:]):
counts = Counter([57, 57, 55, 57, 76, 78, 57, 45, 43, 78, 43, 76, 43, 78, 57, 45, 57, 76, 43, 43, 76])

print(counts.most_common(3))      # [(57, 6), (43, 5), (76, 4)]
print(counts.most_common()[-3:])  # [(78, 3), (45, 2), (55, 1)]

If ties exist in frequency, Counter preserves the order in which items were first encountered.

Updating, Subtracting, and Summing

You can merge new observations into an existing Counter with .update(), or sum all counts cleanly with .total() (added in Python 3.10):

counts = Counter(["a", "b", "a"])
counts.update(["b", "c"])  # adds counts instead of overwriting keys!
print(counts)              # Counter({'a': 2, 'b': 2, 'c': 1})
print(counts.total())      # 5

Notice that dict.update() overwrites matching keys, whereas Counter.update() adds the counts together.

Going Further with Counter

Once you are comfortable with basic frequency counting, Counter also powers some neat advanced AoC patterns:

  • Multiset arithmetic: subtracting inventories or taking intersections (+, -, &, |) in Modern Python Ergonomics.
  • Frequency compression for huge simulations: tracking counts of identical states instead of simulating millions of individual items in Caching and Dynamic Programming.