Python Collections Module
The collections module provides specialized container datatypes that solve common programming problems more elegantly than plain dict, list, or tuple. Each type is designed for a specific use case.
collections.Counter
Counter counts hashable objects. It's a dict subclass where elements are keys and counts are values:
Counter Arithmetic
Counters support set-like operations:
collections.defaultdict
defaultdict extends dict with a factory function for missing keys, eliminating the need for setdefault() or if key not in d checks:
The factory function can be any callable:
collections.deque
deque (double-ended queue) supports efficient O(1) append and pop from both ends. Regular lists have O(n) cost for insert(0, x) and pop(0):
maxlen: Bounded Deque
The maxlen parameter creates a fixed-size deque โ old items are automatically discarded when new ones are added:
This is perfect for sliding windows, recent-items caches, and undo history.
collections.namedtuple
namedtuple creates a tuple subclass with named fields โ lightweight, immutable records without the weight of a full class:
Use namedtuple when you need immutable records that should be memory-efficient and tuple-compatible. For mutable records or validation, prefer @dataclass.
collections.OrderedDict
Before Python 3.7, regular dict did not guarantee insertion order. OrderedDict was the solution. Since Python 3.7+, regular dicts maintain insertion order, but OrderedDict still has one advantage: move_to_end():
OrderedDict is useful for LRU cache implementations and when you specifically need move_to_end semantics.
collections.ChainMap
ChainMap groups multiple dictionaries into a single view. Lookups search through the maps in order:
ChainMap is ideal for layered configuration (env > config file > defaults) without copying data.
Quick Reference
| Type | Use Case | Key Feature |
|---|---|---|
Counter | Count occurrences | most_common(), arithmetic |
defaultdict | Group/accumulate | Auto-initializes missing keys |
deque | Queue/stack | O(1) both-end ops, maxlen |
namedtuple | Lightweight records | Named fields, still a tuple |
OrderedDict | Ordered mapping | move_to_end() |
ChainMap | Layered config | Multi-dict view |
Knowledge Check
What does `Counter('aabbc')['z']` return?
A `deque` with `maxlen=3` currently holds `[1, 2, 3]`. What happens when you call `d.append(4)`?
Why use `defaultdict(list)` instead of a regular `dict` when grouping items?