collections.Counter()
CollectionsA dict subclass for counting hashable objects. Most common element tracking.
Signature
Counter(iterable)
Returns
CounterExample
from collections import Counter
words = 'the cat sat on the mat'.split()
c = Counter(words)
print(c.most_common(2)) # [('the', 2), ('cat', 1)]About collections.Counter()
collections.Counter is a Python collections function with the signature Counter(iterable). A dict subclass for counting hashable objects. Most common element tracking. It returns a value of type Counter.
Python provides a rich set of built-in functions and standard library modules that cover common programming tasks. Understanding these functions helps you write more idiomatic, efficient Python code. The collections.Counterfunction is commonly used in data processing, web development, scripting, and automation tasks.
When working with collections.Counter(), consider edge cases like empty inputs, None values, and type mismatches. Python's duck typing means many built-in functions work with any object that implements the required protocol (e.g., __len__ for len(), __iter__ for iteration). This flexibility is a key strength of Python's design philosophy.