Frequency counting
Tally repeated values in a sequence or stream.
Python · Class
Counter is a dict subclass for tallying hashable objects. It maps each element to its count and supports specialized counting, comparison, and multiset operations.
Counter stores each hashable element as a dictionary key and its tally as the associated value. It accepts an iterable or mapping, supports dictionary-style access and specialized tally methods, and provides arithmetic and multiset operations for combining counters.
class collections.Counter([iterable-or-mapping])| Name | Type | Description |
|---|---|---|
iterable_or_mapping | iterable or mapping | Optional iterable whose elements are counted, or mapping/Counter providing element-count pairs. |
A Counter mapping hashable elements to their counts.
from collections import Counter
counts = Counter("banana")
print(counts.most_common(2))
counts.update("band")
print(counts["a"], counts.total())Counts characters, selects the two most frequent entries, adds more observations, and totals all counts.
Tally repeated values in a sequence or stream.
Combine independent tally results using arithmetic operations.
Find the most frequent elements in collected data.
Counter is a dict subclass that maps hashable elements to their counts. An iterable contributes one count for each element, while a mapping or another Counter initializes explicit counts.
Follow-up: What happens when a missing key is read? The page documents Counter's dictionary-like behavior and examples; verify the missing-key rule in the current method details before relying on it.
The class provides arithmetic operations for combining counters. Addition and subtraction combine corresponding counts, while intersection and union use the minimum and maximum counts respectively.
Follow-up: Which results represent multisets? The documentation describes multisets as counters whose counts are greater than zero.
Counter includes methods beyond dictionaries for tally workflows, including operations for examining repeated elements and combining counts. It also supports dictionary operations because it subclasses dict.
Follow-up: What should be checked when counts can be nonpositive? Determine whether the particular method includes zero or negative counts, since multiset results are described using positive counts.
collections.defaultdictcollections.dequedictCounter.elements()Counter.most_common()Counter.update()