Sub topic 13
A checklist for choosing a structure
This chapter assumes you know Python lists, dictionaries and sets, can read Big-O notation, and have seen the structures covered earlier: arrays, hash tables, deques, heaps, ordered structures and graphs. Here you combine them into a repeatable decision process.
The checklist
Work through these steps in order. Stop when one structure clearly fits.
- List the operations. Write down what the program must do: look up by key, check membership, insert, delete, find the minimum, find a neighbor, traverse relationships.
- Estimate how often each runs. One lookup in a program that runs once does not matter. A million lookups do.
- Check the data size. For a few dozen items, almost any structure is fast enough. Simplicity wins.
- Check for ordering needs. Do you need arrival order, sorted order, or no order at all?
- Check the key type. Hash tables need hashable keys. Mutable values such as lists cannot be keys.
- Match to a cost profile. Pick the structure that makes your most frequent operation cheap.
- Measure if it is close. Memory layout and constant factors can outweigh Big-O differences.
Matching operations to structures
| Dominant operation | Good choice | Typical cost |
|---|---|---|
| Access by position | list | O(1) |
| Membership or lookup by key | set or dict | O(1) average |
| Add and remove at both ends | deque | O(1) |
| Repeatedly get the smallest or largest | heap (`heapq`) | O(log n) |
| Next larger value, ranges | sorted list with `bisect` or a balanced tree | O(log n) search |
| Relationships between items | dict-based adjacency list | O(1) to find a node's neighbors |
| Prefix search on strings | trie | O(length of prefix) |
| Connected groups | union-find | near O(1) per operation |
A worked example
Suppose you must read a stream of 100,000 user IDs and report whether each one was seen before.
- Operations: one membership test and one insert per ID.
- Frequency: 100,000 of each.
- Order: not needed.
- Keys: integers, which are hashable.
A set fits. A list would scan up to n items for each test.
names_list = ["ada", "grace", "alan"]
names_set = set(names_list)
print("grace" in names_list) # True, scans the list: O(n)
print("grace" in names_set) # True, hash lookup: O(1) on averageNow change the requirement: for each new ID, also find the next larger ID already seen. A hash table cannot answer that, because it has no order. Step 4 points to a sorted structure.
import bisect
sorted_ids = [10, 20, 30, 40]
i = bisect.bisect_left(sorted_ids, 25)
print(i, sorted_ids[i]) # 2 30
bisect.insort(sorted_ids, 25)
print(sorted_ids) # [10, 20, 25, 30, 40]The search is O(log n). The insert still shifts elements, so it costs O(n). If inserts dominate on very large data, a balanced tree is a better fit. For moderate sizes, the sorted list is often faster in practice because its memory is contiguous.
Combining structures
Real problems often need more than one structure. Breadth-first search uses a dictionary for the graph, a set for visited nodes, and a deque as the queue.
from collections import deque
def bfs_order(graph, start):
seen = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in seen:
seen.add(neighbor)
queue.append(neighbor)
return order
graph = {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}
print(bfs_order(graph, "a")) # ['a', 'b', 'c', 'd']Each piece answers one question from the checklist. The dict gives neighbors, the set answers "seen before?", and the deque removes from the front in O(1).
Exercises
Exercise
A scheduler repeatedly needs the task with the earliest deadline, and new tasks arrive constantly. Which structure fits, and why not a sorted list?
Show answer
A heap. Each push and pop costs O(log n). A sorted list finds the minimum quickly, but each insert shifts elements and costs O(n).
Exercise
You need to store visited grid positions as (row, column) pairs and test membership often. Which structure and key type do you choose?
Show answer
A set of tuples. Tuples are immutable and hashable, so they work as set members, and membership is O(1) on average. Lists would raise a TypeError.