Phase 16 of 25 · Topic 16.1

collections.Counter & Frequency Multiset Arithmetic

1Concept

`collections.Counter` is a dict subclass designed for counting hashable items. It supports frequency tallying via `.most_common(N)` and multiset mathematical operations (addition `+`, subtraction `-`, intersection `&`, and union `|`).

2Architecture Diagram

Counter('abracadabra') ---> {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
.most_common(2) ---> [('a', 5), ('b', 2)]

3Code Example

Python 3.12
from collections import Counter

logs = ["404", "200", "500", "200", "404", "200", "403", "200"]
status_counts = Counter(logs)

print(f"Top 2 Status Codes: {status_counts.most_common(2)}")
print(f"Total Requests:     {status_counts.total()}")

# Multiset arithmetic
batch_a = Counter(apple=3, orange=2)
batch_b = Counter(apple=1, orange=4, banana=2)
print(f"Combined Inventory: {batch_a + batch_b}")

4Expected Output

Top 2 Status Codes: [('200', 4), ('404', 2)]
Total Requests:     8
Combined Inventory: Counter({'orange': 6, 'apple': 4, 'banana': 2})

5Key Takeaways

  • Missing keys in a Counter return `0` instead of raising `KeyError`.
  • Subtracting Counters removes non-positive counts automatically in `+`/`-` operations.
  • `counter.total()` (Python 3.10+) computes the sum of all frequencies.