ID EN
Collections

Counter

Python 3.11

A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

Syntax

PYTHON
class collections.Counter([iterable-or-mapping])

Examples

Example 1
PYTHON
>>> c = Counter()                            a new, empty counter
>>> c = Counter('gallahad')                  a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2})       a new counter from a mapping
>>> c = Counter(cats=4, dogs=8)              a new counter from keyword args
Example 2
PYTHON
>>> c = Counter(['eggs', 'ham'])
>>> c['bacon']                               count of a missing element is zero
0
Example 3
PYTHON
>>> c['sausage'] = 0                         counter entry with a zero count
>>> del c['sausage']                         del actually removes the entry
Example 4
PYTHON
>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']
Example 5
PYTHON
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]

See Also

Counter dict hashable Counter KeyError dict Counter elements()