Built-in Data Structuresmedium

collections Module

The collections module provides specialized container types: deque, defaultdict, Counter, OrderedDict, namedtuple, ChainMap.

Memory anchor

collections = the specialty aisle in the grocery store. deque is a double-ended conveyor belt, Counter is a tally clicker, defaultdict is a vending machine that auto-stocks when empty.

Expected depth

deque: O(1) append/pop from both ends (use instead of list for queues). defaultdict(int/list): auto-initializes missing keys — eliminates KeyError boilerplate. Counter(iterable): counts elements, most_common(n), arithmetic operations. namedtuple: immutable, memory-efficient, positional and named access. OrderedDict: dict with move_to_end() for LRU patterns (less needed since 3.7 dicts are ordered).

Deep — senior internals

deque is implemented as a doubly-linked list of fixed-size blocks — O(1) at both ends, O(n) random access. deque(maxlen=N) creates a circular buffer that auto-discards the oldest item when full — useful for sliding windows. Counter extends dict — missing keys return 0, not KeyError. Counter subtraction clamps at 0 (use subtract() for signed). namedtuple creates a new class with __slots__ equivalent performance. dataclasses (Python 3.7+) is the modern alternative to namedtuple when you need mutability or defaults.

🎤Interview-ready answer

collections is one of the most useful standard library modules in interviews. Counter for frequency counting in O(n). defaultdict to eliminate boilerplate. deque for O(1) queue operations. I use collections.deque(maxlen=N) for sliding window problems — it automatically evicts old elements. namedtuple for lightweight value objects. Knowing these lets you write cleaner, more efficient code than with just list and dict.

Common trap

Counter['missing_key'] returns 0, not KeyError. This is intentional and useful, but be careful if you're checking for key presence — 'key' in counter is the correct check, not counter['key'].

Related concepts