Data structures
Data structures
Section titled “Data structures”Built-in
Section titled “Built-in”xs = [1, 2, 3] # list — ordered, mutable (dynamic array)t = (1, 2) # tuple — ordered, immutabled = {"a": 1, "b": 2} # dict — key–value; insertion order preserved (3.7+)s = {1, 2, 3} # set — unordered, unique, hashable elements onlyf = frozenset({1, 2}) # frozenset — immutable setname = "hello" # str — immutable character sequenceb = b"bytes" # bytes — immutable; bytearray — mutableEmpty: [] list, {} dict, set() set (not {} — that’s a dict).
Mutability and hashability
Section titled “Mutability and hashability”- Mutable = can change in place (list, dict, set). Immutable = can’t (tuple, str, frozenset, int).
- Only hashable types can be dict keys or set elements. Immutable built-ins (tuple, str, frozenset, int, float) are hashable; list, dict, and set are not. That’s why you can’t put a list in a set or use it as a dict key — use a tuple instead.
Standard library and third-party
Section titled “Standard library and third-party”- collections:
deque(double-ended queue),defaultdict,Counter,OrderedDict,namedtuple - heapq: min-heap on a list
- queue:
Queue,LifoQueue,PriorityQueue(thread-safe) - array: typed arrays
Third-party: NumPy, Pandas, and graph/tree libs for specialized needs.
When to use what
Section titled “When to use what”| Use case | Structure |
|---|---|
| Ordered sequence you need to change | list (append, insert, remove) — default for “a sequence of things” |
| Ordered sequence that shouldn’t change | tuple (return values, dict keys, coordinates) |
| Look up by key | dict (names → values, id → record) |
| Unique items or fast “is x in here?” | set (order doesn’t matter, no duplicates) |
| Queue or stack from both ends | deque (use instead of list when you pop from the front often, e.g. BFS) |
| Smallest item, priority queue, “top K” | heapq (min-heap) |
Why this matters for algorithms
Section titled “Why this matters for algorithms”These structures are the base you’ll use when learning algorithms:
- list — dynamic array (indexing, sorting, DP)
- dict — O(1) lookup and graph adjacency
- set — visited sets and uniqueness
- tuple — immutable pairs (edges, coords)
- deque — BFS and queues
- heapq — Dijkstra and heaps
See the Algorithms section for more.