The right tool for common patterns — knowing these separates fluent Python from homework Python
Picking the right container eliminates entire classes of bugs and performance issues. list.insert(0, x) is O(n); deque.appendleft(x) is O(1). x in list is O(n); x in set is O(1). Counter replaces 5 lines of frequency-counting boilerplate with one. Reaching for the right tool without being told is what separates Python fluency from just knowing the syntax.
list — ordered, mutable, duplicates allowed. tuple — ordered, immutable, hashable (safe as dict key). set — unordered, unique, O(1) membership. dict — key→value, O(1) lookup, ordered by insertion since 3.7. The collections module extends these: Counter counts, defaultdict never raises KeyError, deque is O(1) at both ends.
The four core built-in containers — each with distinct trade-offs around ordering, mutability, and lookup speed. Choosing the right one prevents entire classes of bugs.
Built-in iteration helpers that eliminate manual index tracking and loop boilerplate. They work with any iterable.
The collections module extends the core containers for specific patterns: counting frequencies, safe default access, and O(1) operations at both ends of a sequence.
A named tuple is a tuple subclass where each position has a name. Immutable, memory-efficient, and prints readably — a lightweight read-only record without the overhead of a full class.
heapq implements a min-heap on a regular list. Use it for priority queues, efficiently retrieving the k smallest/largest items, and graph algorithms like Dijkstra's.
Enum defines a fixed set of named constants. It replaces magic strings and numbers with self-documenting, type-safe names and makes it clear the set of values is closed.
Use auto() when the exact value doesn't matter. If values must be specific (e.g. stored in a DB), assign them explicitly: PENDING = "pending".