Python Function Reference

collections.Counter

Count how many times each item occurs.

Python 3.13
collections.Counter([iterable])

Parameters

iterableIterable | Mappingoptional
The items to count, or a dictionary with ready counts.

Return value

A Counter object, a dictionary subclass of the form {item: count}.

Examples

Counting list items

Python 3.13
from collections import Counter

print(Counter(['apple', 'pear', 'apple']))
Counter({'apple': 2, 'pear': 1})

Most common characters

Python 3.13
from collections import Counter

counts = Counter('abracadabra')
print(counts.most_common(2))
[('a', 5), ('b', 2)]

Details

A missing item gives 0 instead of KeyError. The most_common(n) method returns the n most frequent items.

See also

Where to learn