Python collections.Counter
Published Jul 7, 2022Updated Mar 5, 2025
Contribute to Docs
A Counter is a data type in the collections module. It is a dict subclass that stores counts for hashable objects. For each key-value pair, the key is the item being counted, and the value is the count of that object. A Counter‘s items are accessed just as in a dictionary, except accessing a missing key will return a 0 value rather than an error.
Note: A Counter will allow negative counts.
Syntax
myCollection = collections.Counter()
A Counter can also be initialized from an iterable or initialized from another mapping.
Additional Methods
A Counter supplies the following additional methods beyond those for a standard dictionary:
.elements(): Returns an iterator for the keys of theCounterrepeating each element as many times as its count. It will ignore items with a count of less than one..most_common(n): Returns thenmost common key-count pairs, in descending order of their counts. Ifnis omitted orNone, the entire contents of theCollectionare returned..subtract(values): Wherevaluesis an iterable or mapping. Matching keys have their values subtracted from the elements in theCounter. Inputs and outputs can be negative or zero..total(): Returns the sum of all the counts.
Other differences from a standard dictionary:
- A
Counterdoes not implement the.fromkeys()method. - The
.update()method adds counter values rather than replacing them, making it the opposite of.subtract()above.
Codebyte Example
The following example creates a Counter from an iterable (a string) and outputs various characteristics of the Counter:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours