Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

collections.Counter

Maps hashable observations to their counts, including explicitly stored zero or negative counts.

Version: Python 3.14; repository image, production runtime not attested

Syntax

collections.Counter()
collections.Counter(iterable_or_mapping, /, **counts)
collections.Counter(**counts)

Maps hashable observations to their counts, including explicitly stored zero or negative counts.

Reading an absent key returns zero. Subtracting counts can leave negative entries in the mapping.

Give Counter an iterable of hashable observations or a mapping of initial counts. A missing subscription yields zero without adding a key. Subtraction retains negative counts and explicitly stored zeros remain keys. Three occurrences of a and two subtractions of c explain the first two outputs; z was never inserted. Counts can also be fractional; for example 0.5 can be stored, though elements() requires integers.

from collections import Counter
c = Counter({"a": 1, "b": 0})
assert c["missing"] == 0 and "missing" not in c
c.subtract("aa")
assert c["a"] == -1 and list(c.elements()) == []
assert "b" in c
assert Counter(a=0.5)["a"] == 0.5 and not Counter()

Examples

import collections
counts = collections.Counter("ababa")
counts.subtract("cc")
print(counts["a"], counts["c"], counts["z"])

Result

3 -2 0

Give Counter an iterable of hashable observations or a mapping of initial counts. A missing subscription yields zero without adding a key. Subtraction retains negative counts and explicitly stored zeros remain keys. Three occurrences of a and two subtractions of c explain the first two outputs; z was never inserted. Counts can also be fractional; for example 0.5 can be stored, though elements() requires integers.

Sources