Python theorytheory 0/50 · 0%
Collections · medium

29. Collections module: Counter, defaultdict, deque

Specialized container types beyond the built-ins.

The `collections` module offers specialized containers that solve common patterns more cleanly than plain dicts/lists.

python
from collections import Counter, defaultdict, deque

Counter(["eth", "eth", "btc"]).most_common(1)   # [("eth", 2)]

groups = defaultdict(list)
groups["stable"].append("USDC")   # no KeyError, auto-creates []

q = deque([1, 2, 3])
q.appendleft(0)
q.popleft()   # O(1), unlike list.pop(0)

`deque` supports O(1) appends/pops from both ends, making it ideal for queues, unlike a list where `.pop(0)` is O(n).

Check your understanding

  1. 1. What does `defaultdict(list)` do when accessing a missing key?

  2. 2. What advantage does `deque` have over `list` for queue operations?

  3. 3. What does `Counter(items).most_common(1)` return?