Sub topic 1
Start with the operations, not the structure
Prerequisites
This chapter assumes you can write Python loops and functions, and that you use lists and dictionaries. You should know roughly what Big-O notation means: it describes how the cost of an operation grows with input size. Later chapters cover Big-O in more detail.
Why start with operations
Many poor data structure choices come from picking a familiar container first, usually a list, and then fitting the problem to it. The better order is to reverse this. First write down what your program must do with the data. Then pick the structure whose cheap operations match that list.
A data structure is a way of organizing data so that some operations are fast and others are slow. No structure is fast at everything. Choosing one means choosing which operations you want to be cheap.
List the operations
For any problem, ask these questions:
- What gets added, and where? At the end, at the front, or anywhere?
- What gets removed, and which item? The oldest, the smallest, or a specific one?
- How do you find an item? By position, by exact value, by prefix, or by range?
- Does order matter? Insertion order, sorted order, or none?
- How often does each operation run? A rare operation can be slow. A hot-loop operation cannot.
- How big can the data get?
Question 5 matters most. A structure that is slow at an operation you run once is fine. The same slowness inside a loop that runs a million times is a bug.
A worked example
Suppose you process a stream of usernames and must report whether each one has appeared before. The operations are:
- Add a username: once per item.
- Check whether a username exists: once per item.
- Order: irrelevant.
A first attempt often uses a list:
def first_repeat_list(names):
seen = []
for name in names:
if name in seen: # scans the list: O(n)
return name
seen.append(name) # O(1) amortized
return None
print(first_repeat_list(["ada", "grace", "alan", "grace"])) # graceThe membership test name in seen is the hot operation, and a list answers it by scanning. Over n names the total cost grows as O(n²). The requirements say "exact-value membership, no order". That points to a set:
def first_repeat_set(names):
seen = set()
for name in names:
if name in seen: # hash lookup: O(1) on average
return name
seen.add(name) # O(1) on average
return None
print(first_repeat_set(["ada", "grace", "alan", "grace"])) # graceSame logic, but the total cost is now O(n) on average. Only the structure changed, and it changed because we named the dominant operation.
Turning requirements into a shortlist
The table maps common requirements to candidates. Later chapters explain each one.
| Dominant operation | Likely candidate |
|---|---|
| Access by position | List (array) |
| Exact lookup or membership | Dictionary or set |
| Remove oldest item first | Queue (deque) |
| Remove newest item first | Stack (list) |
| Always get smallest or largest | Heap |
| Sorted order, ranges, neighbors | Sorted list or search tree |
| Relationships between items | Graph |
When requirements conflict
Sometimes two operations pull in opposite directions. A set gives fast membership but no order. A sorted list gives order but slow inserts. In that case, use frequencies to decide. If you insert once and query many times, build the structure once and favor the query. If you insert constantly and query rarely, favor the insert. You can also keep two structures in sync, such as a list for order and a set for membership, at the cost of more memory and more code.
Exercise
A program reads 500,000 task records. It repeatedly removes the task with the earliest deadline and occasionally adds new tasks. Order of the remaining tasks does not matter. Name the dominant operations and say which structure family fits, and which structure to avoid.
Show answer
The dominant operations are "insert a task" and "remove the item with the smallest deadline". A heap (priority queue) fits, since it returns the smallest item cheaply and supports efficient inserts. A plain list is a poor choice if you scan for the minimum on every removal, because each removal costs O(n).
Exercise
You need to check, many times, whether an ID is among 100,000 known IDs. Which operations did you identify, and which built-in Python type fits?
Show answer
The operations are one-time build, then many exact-value membership checks, with no need for order. A set fits, because membership is an average O(1) hash lookup instead of an O(n) list scan.