Codectionary / Developer documentation / Python

Counter Frequency Tables

Counter counts hashable items and supports frequency queries without manually initializing each key. Missing counts read as zero. Run as a Python 3.11+ script.

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"])
  1. Expected output: [('red', 3), ('blue', 2)] 0
  2. 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

Specifications & further reading