Counter() Provides an Easy Way to Count How Many Items of Each Type Are In Python Collection Objects

Counter is a member of the collections module.

You can give Counter() any iterator, and it will return a hashmap (like a dictionary) with the counts.

For example, let’s look at the following string: s = "I love programming in Python!"

Remember, a string is an iterable that iterates over individual characters.

Now let’s count how many of each character appear in the string:

from collections import Counter

s = "I love programming in Python!"
counts = Counter(s)

The result is,

>>> Counter({' ': 4, 'o': 3, 'n': 3, 'r': 2, 'g': 2, 'm': 2, 'i': 2, 'I': 1, 'l': 1,
'v': 1, 'e': 1, 'p': 1, 'a': 1, 'P': 1, 'y': 1, 't': 1, 'h': 1, '!': 1})

The counts object works like a Python dictionary. Writing, counts['g'], for example, will return the number of g’s in the string, which is 2.

If you just want to know which characters are in the string, but don’t care about the counts, you can use a set:

chars = set(s)

>>> {'a', '!', 'g', 'e', 'p', 'i', 'h', 'l', 'P', 'm', 'o', ' ', 'v', 'y', 't', 'I', 'n', 'r'}