← All languages
Python function of the day
Random

collections.Counter

Count hashable objects in an iterable, returning a dictionary subclass.

Description

The collections.Counter class is a dict subclass for counting hashable objects. Elements are stored as dictionary keys and their counts as dictionary values. Counts can be any integer value, including zero or negative counts.

Counter can be initialized with an iterable, a mapping, or keyword arguments. It provides convenient methods like most_common() to list elements by frequency, elements() to iterate over elements repeating each as many times as its count, and subtract() to subtract counts. It also supports arithmetic operations like addition and subtraction between Counters.

Counter is invaluable for frequency analysis, histograms, multiset operations, and tallying. Common use cases include word frequency counting, vote tallying, inventory tracking, and finding the most common elements in a dataset.

Arguments

NameDescriptionOptional
iterable_or_mapping An iterable of elements to count, a mapping of element-count pairs, or keyword arguments. Yes

Example

from collections import Counter
Counter('abracadabra')  # Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
Counter([1, 1, 2, 3, 3, 3]).most_common(2)  # Returns [(3, 3), (1, 2)]

Reference