Counter: a shortcut to counting iterables in Python

A nice little helper from the Python standard library

Alex Strick van Linschoten


January 1, 2022

I came across this special dictionary type while reading an earlier chapter of ‘Robust Python’ the other day. It’s perhaps best illustrated with an example:

from collections import Counter
# returns Counter({1: 2, 2: 1, 3: 1})

Counter('The Netherlands'.lower())
# returns Counter({'e': 3, 't': 2, 'h': 2, 'n': 2, ' ': 1, 'r': 1, 'l': 1, 'a': 1, 'd': 1, 's': 1})

I had no idea this existed, and of course usually default to some kind of a cookie-cutter loop when trying get counts of elements and put those counts into a dict.

To get the inividual elements, just call the elements method on the Counter object. To get the most common n elements, call the most_common(n) method. To get the total number of counts inside the dictionary, use the total method. To reset all the counts, use the clear method.

Just a nice little set of functionality, hiding in plain sight inside the Python standard library.

Photo by Ibrahim Rifath on Unsplash