collections.Counter

The snippet below shows how autoclasstoc can be used to document the collections.Counter class from the Python standard library. Even though this class has a lot of documentation, the TOC makes it easy to (i) quickly get a sense for the what the class can do and (ii) quickly navigate to the detailed description for any method.

.. autoclass:: collections.Counter
  :members:
  :private-members:
  :special-members:
  :inherited-members:
  :undoc-members:

  .. autoclasstoc::
class collections.Counter(**kwds)[source]

Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values.

>>> c = Counter('abcdeabcdabcaba')  # count elements from a string
>>> c.most_common(3)                # three most common elements
[('a', 5), ('b', 4), ('c', 3)]
>>> sorted(c)                       # list all unique elements
['a', 'b', 'c', 'd', 'e']
>>> ''.join(sorted(c.elements()))   # list elements with repetitions
'aaaaabbbbcccdde'
>>> sum(c.values())                 # total of all counts
15
>>> c['a']                          # count of letter 'a'
5
>>> for elem in 'shazam':           # update counts from an iterable
...     c[elem] += 1                # by adding 1 to each element's count
>>> c['a']                          # now there are seven 'a'
7
>>> del c['b']                      # remove all 'b'
>>> c['b']                          # now there are zero 'b'
0
>>> d = Counter('simsalabim')       # make another counter
>>> c.update(d)                     # add in the second counter
>>> c['a']                          # now there are nine 'a'
9
>>> c.clear()                       # empty the counter
>>> c
Counter()

Note: If a count is set to zero or reduced to zero, it will remain in the counter until the entry is deleted or the counter is cleared:

>>> c = Counter('aaabbc')
>>> c['b'] -= 2                     # reduce the count of 'b' by two
>>> c.most_common()                 # 'b' is still in, but its count is zero
[('a', 3), ('c', 1), ('b', 0)]

Public Methods:

__init__(**kwds)

Create a new, empty Counter object.

__missing__(key)

The count of elements not in the Counter is zero.

most_common([n])

List the n most common elements and their counts from the most common to the least.

elements()

Iterator over elements repeating each as many times as its count.

fromkeys(iterable[, v])

Returns a new dict with keys from iterable and values equal to value.

update(**kwds)

Like dict.update() but add counts instead of replacing them.

subtract(**kwds)

Like dict.update() but subtracts counts instead of replacing them.

copy()

Return a shallow copy.

__reduce__()

helper for pickle

__delitem__(elem)

Like dict.__delitem__() but does not raise KeyError for missing values.

__repr__()

Return repr(self).

__add__(other)

Add counts from two counters.

__sub__(other)

Subtract count, but keep only results with positive counts.

__or__(other)

Union is the maximum of value in either of the input counters.

__and__(other)

Intersection is the minimum of corresponding counts.

__pos__()

Adds an empty counter, effectively stripping negative and zero counts

__neg__()

Subtracts from an empty counter.

__iadd__(other)

Inplace add from another counter, keeping only positive counts.

__isub__(other)

Inplace subtract counter, but keep only results with positive counts.

__ior__(other)

Inplace union is the maximum of value from either counter.

__iand__(other)

Inplace intersection is the minimum of corresponding counts.

Inherited from dict

__repr__()

Return repr(self).

__getattribute__(name, /)

Return getattr(self, name).

__lt__(value, /)

Return self<value.

__le__(value, /)

Return self<=value.

__eq__(value, /)

Return self==value.

__ne__(value, /)

Return self!=value.

__gt__(value, /)

Return self>value.

__ge__(value, /)

Return self>=value.

__iter__()

Implement iter(self).

__init__(*args, **kwargs)

__len__()

Return len(self).

__getitem__

x.__getitem__(y) <==> x[y]

__setitem__(key, value, /)

Set self[key] to value.

__delitem__(key, /)

Delete self[key].

__contains__(key, /)

True if D has a key k, else False.

__sizeof__()

get(k[,d])

setdefault(k[,d])

pop(k[,d])

If key is not found, d is returned if given, otherwise KeyError is raised

popitem()

2-tuple; but raise KeyError if D is empty.

keys()

items()

values()

update([E, ]**F)

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

fromkeys([value])

Returns a new dict with keys from iterable and values equal to value.

clear()

copy()

Private Methods:

_keep_positive()

Internal method to strip elements with a negative or zero count


__add__(other)[source]

Add counts from two counters.

>>> Counter('abbb') + Counter('bcc')
Counter({'b': 4, 'c': 2, 'a': 1})
__and__(other)[source]

Intersection is the minimum of corresponding counts.

>>> Counter('abbb') & Counter('bcc')
Counter({'b': 1})
__contains__(key, /)

True if D has a key k, else False.

__delitem__(elem)[source]

Like dict.__delitem__() but does not raise KeyError for missing values.

__eq__(value, /)

Return self==value.

__ge__(value, /)

Return self>=value.

__getattribute__(name, /)

Return getattr(self, name).

__getitem__()

x.__getitem__(y) <==> x[y]

__gt__(value, /)

Return self>value.

__hash__ = None
__iadd__(other)[source]

Inplace add from another counter, keeping only positive counts.

>>> c = Counter('abbb')
>>> c += Counter('bcc')
>>> c
Counter({'b': 4, 'c': 2, 'a': 1})
__iand__(other)[source]

Inplace intersection is the minimum of corresponding counts.

>>> c = Counter('abbb')
>>> c &= Counter('bcc')
>>> c
Counter({'b': 1})
__init__(**kwds)[source]

Create a new, empty Counter object. And if given, count elements from an input iterable. Or, initialize the count from another mapping of elements to their counts.

>>> c = Counter()                           # a new, empty counter
>>> c = Counter('gallahad')                 # a new counter from an iterable
>>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
>>> c = Counter(a=4, b=2)                   # a new counter from keyword args
__ior__(other)[source]

Inplace union is the maximum of value from either counter.

>>> c = Counter('abbb')
>>> c |= Counter('bcc')
>>> c
Counter({'b': 3, 'c': 2, 'a': 1})
__isub__(other)[source]

Inplace subtract counter, but keep only results with positive counts.

>>> c = Counter('abbbc')
>>> c -= Counter('bccd')
>>> c
Counter({'b': 2, 'a': 1})
__iter__()

Implement iter(self).

__le__(value, /)

Return self<=value.

__len__()

Return len(self).

__lt__(value, /)

Return self<value.

__missing__(key)[source]

The count of elements not in the Counter is zero.

__ne__(value, /)

Return self!=value.

__neg__()[source]

Subtracts from an empty counter. Strips positive and zero counts, and flips the sign on negative counts.

__new__(**kwargs)
__or__(other)[source]

Union is the maximum of value in either of the input counters.

>>> Counter('abbb') | Counter('bcc')
Counter({'b': 3, 'c': 2, 'a': 1})
__pos__()[source]

Adds an empty counter, effectively stripping negative and zero counts

__reduce__()[source]

helper for pickle

__repr__()[source]

Return repr(self).

__setitem__(key, value, /)

Set self[key] to value.

__sizeof__() size of D in memory, in bytes
__sub__(other)[source]

Subtract count, but keep only results with positive counts.

>>> Counter('abbbc') - Counter('bccd')
Counter({'b': 2, 'a': 1})
_keep_positive()[source]

Internal method to strip elements with a negative or zero count

clear() None.  Remove all items from D.
copy()[source]

Return a shallow copy.

elements()[source]

Iterator over elements repeating each as many times as its count.

>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']

# Knuth’s example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> product = 1 >>> for factor in prime_factors.elements(): # loop over factors … product *= factor # and multiply them >>> product 1836

Note, if an element’s count has been set to zero or is a negative number, elements() will ignore it.

classmethod fromkeys(iterable, v=None)[source]

Returns a new dict with keys from iterable and values equal to value.

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
most_common(n=None)[source]

List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts.

>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
pop(k[, d]) v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised

popitem() (k, v), remove and return some (key, value) pair as a

2-tuple; but raise KeyError if D is empty.

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
subtract(**kwds)[source]

Like dict.update() but subtracts counts instead of replacing them. Counts can be reduced below zero. Both the inputs and outputs are allowed to contain zero and negative counts.

Source can be an iterable, a dictionary, or another Counter instance.

>>> c = Counter('which')
>>> c.subtract('witch')             # subtract elements from another iterable
>>> c.subtract(Counter('watch'))    # subtract elements from another counter
>>> c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch
0
>>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
-1
update(**kwds)[source]

Like dict.update() but add counts instead of replacing them.

Source can be an iterable, a dictionary, or another Counter instance.

>>> c = Counter('which')
>>> c.update('witch')           # add elements from another iterable
>>> d = Counter('watch')
>>> c.update(d)                 # add elements from another counter
>>> c['h']                      # four 'h' in which, witch, and watch
4
values() an object providing a view on D's values