Syntax
Counter(iterable); counts.most_common(n); counts[key]Examples
Counter Frequency Tables
Run as a Python 3.11+ script.
from collections import Counter
counts = Counter(["red", "blue", "red", "green", "red"])
counts.update(["blue"])
print(counts.most_common(2))
print(counts["yellow"])- Expected output: [('red', 3), ('blue', 2)] 0
- update adds frequencies instead of replacing them. most_common returns item/count pairs; a missing lookup returns zero without inserting a new key.
Best practices
- Use hashable keys such as strings or tuples.
- Choose an explicit tie-breaking sort when equal-frequency order is a business requirement.
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference