Complexity: Beginner
- ▸Tables accumulate: an events table that adds 2 million rows a day holds 730 million after a year.
- ▸Samples are small on purpose, so a bad growth rate stays invisible until launch.
- ▸Reference data grows too: the product catalog gets longer every month, and so do user lists and blocklists.
- ▸A job that reprocesses full history each night does more work every night, even with steady traffic.
Counting steps instead of seconds
Constant, linear, quadratic
| rows (n) | O(1) steps | O(n) steps | O(n²) steps |
|---|---|---|---|
| 10 | 1 | 10 | 100 |
| 1,000 | 1 | 1,000 | 1,000,000 |
| 1,000,000 | 1 | 1,000,000 | 1,000,000,000,000 |
On a 1,000-row sample every stage finishes in a blink. At 1,000,000 rows the quadratic stage runs for hours and the report misses 06:00.
A deduplication script takes 2 seconds on 10,000 rows. Its work is quadratic. Roughly how long will it take on 100,000 rows?
How a dict finds a key without searching
When you write totals["u42"] = 7, Python runs the key through a hash function, which turns it into a large integer. That integer picks a slot in an internal table, and the value is stored in that slot. Reading totals["u42"] later repeats the calculation, lands on the same slot and reads the value. No other key gets examined, so the size of the dict barely affects the cost. Now and then 2 keys land on the same slot and Python checks a few nearby slots, which keeps the average to a handful of steps. A set uses the same kind of table, storing keys with no values attached.
A list has no such shortcut when you search by value. The in operator works on lists too, but Python answers x in some_list by comparing x with each item in turn, starting at index 0, until it finds a match or runs out of items. Reading by position is a different story: some_list[3] jumps straight to slot 3, so indexing is O(1).
Searching a list vs. checking a set
| operation | example | cost |
|---|---|---|
| read by index | `events[3]` | O(1) |
| length | `len(events)` | O(1), the size is stored |
| append to the end | `events.append(row)` | O(1) on average |
| dict read or write | `totals[user]` | O(1) on average |
| set membership | `user in blocked` | O(1) on average |
| set add | `seen.add(event_id)` | O(1) on average |
| list membership | `user in blocked_list` | O(n) |
| remove by value | `events.remove(row)` | O(n) |
| insert at the front | `events.insert(0, row)` | O(n), every item shifts right |
Turning a list into a lookup
Pipelines often receive reference data as a list: valid country codes, blocked users, known product ids. Convert it once with set(...), or build a dict when each key needs a value, and every later check becomes constant time. not in asks the opposite question at the same cost. The conversion walks the list once, so it pays for itself as soon as you check more than a couple of values.
Each row does 2 lookups, one in the set and one in the dict, and both stay constant time however long the blocklist or the artist table gets. The loop over plays is a single pass, the shape the next section takes apart.
Where list costs grow
Lists stay fast at their end and slow everywhere else. append writes into the next free slot, so adding the 2,000,001st id costs the same as adding the 3rd. insert(0, row) must move every existing item one slot to the right to open a gap at index 0: on a list of 2,000,000 ids, that is 2,000,000 moves for a single insert. remove pays twice. It first searches from the front for the value, then shifts every later item left to close the gap. A set keeps no positions to shift, so adding an id or checking membership costs the same at any size.
users is a list of ids and user_set = set(users). Which line does about the same work whether there are 2,000 ids or 2,000,000?
A single pass with constant work per row
The pattern is a for loop over the input where every operation inside is O(1). The body may do arithmetic and comparisons, read or write a dict, check a set or call append. The cost is n rows times a fixed cost per row, which grows in step with n.
plays = [["Nova", 210],["Rook", 185],["Nova", 240],["Ivy", 199],["Rook", 60],]totals = {}steps = 0for play in plays:artist = play[0]seconds = play[1]if artist in totals:totals[artist] = totals[artist] + secondselse:totals[artist] = secondssteps = steps + 1print(totals)print("rows:", len(plays), "steps:", steps)
Each row costs a dict check and a dict write, so steps match rows.
Built-ins that loop for you
Some one-line calls hide a full pass over their input. sum(values) reads every item, and so do min(values) and max(values), which makes each of them O(n). set(values) and list(values) copy every item, also O(n). A list's in check is a pass that can stop early. len(values) is the exception: the list stores its own length, so asking for it is O(1).
Calling several of these one after another keeps the job linear. summarize below makes 3 passes over the same list for about 3n steps. Double the rows and the steps still only double.
Several answers from one pass
| rows (n) | 1 loop | 2 loops in sequence |
|---|---|---|
| 1,000 | 1,000 | 2,000 |
| 2,000 | 2,000 | 4,000 |
| 1,000,000 | 1,000,000 | 2,000,000 |
How does the work in report grow as rows grows?
A loop inside a loop
The hidden inner loop
It reads as a single loop. On a list, though, event_id not in seen walks seen from the front, and seen grows as the function runs. The animation writes that hidden walk out as a real inner loop so you can watch the comparisons pile up.
event_ids = ["e1", "e2", "e3", "e2", "e4"]seen = []checks = 0for event_id in event_ids:found = Falsefor old_id in seen:checks = checks + 1if old_id == event_id:found = Truebreakif not found:seen.append(event_id)print(seen)print("checks:", checks)
The inner loop is what event_id not in seen does when seen is a list.
The fix: let a set do the remembering
The set answers event_id not in seen in constant time however many ids it holds, so the loop is n iterations of fixed work: O(n). The list unique stays because it keeps ids in their arrival order, which a set does not promise. At 1,000,000 events, about 500 billion comparisons become about 1 million hash lookups.
Other one-liners that hide a loop
- values.count(x) inside a loop: each call compares every item in the list.
- max(values) inside a loop over values: recomputes the same answer on every row. Compute it once, before the loop.
- rows.remove(row) inside a loop: each removal searches the list, then shifts everything after the gap.
- rows.insert(0, row) inside a loop: each insert shifts every item already in the list.
Matching 2 inputs: O(n × m)
| plays | artists | comparisons |
|---|---|---|
| 1,000 | 50 | 50,000 |
| 1,000,000 | 50,000 | 50,000,000,000 |
| plays | artists | steps |
|---|---|---|
| 1,000 | 50 | 1,050 |
| 1,000,000 | 50,000 | 1,050,000 |
| line inside the loop | with a list | with a set |
|---|---|---|
| the loop itself | n iterations | n iterations |
| `event_id not in seen` | grows with `seen`: O(n) | 1 hash lookup: O(1) |
| remembering the id | `seen.append(event_id)`: O(1) | `seen.add(event_id)`: O(1) |
Which change turns this function from O(n²) into O(n)?
Rules for reading growth
- Find n. Name what grows: rows in a list, keys in a dict, ids in a set.
- Count loops over the input. Each costs n. A loop over a fixed range, such as range(7), costs a constant.
- Sequential loops add. A loop followed by another loop over the same rows is n + n.
- Nested loops multiply. A loop inside a loop costs the outer count times the inner count.
- Look inside calls. An O(n) built-in or helper inside a loop is an inner loop.
- Keep the biggest term. Drop constant factors and anything that grows more slowly.
Why constants and small terms drop out
| steps counted | Big O | why |
|---|---|---|
| 5 | O(1) | no n at all |
| 3n + 5 | O(n) | drop the factor 3 and the + 5 |
| n² + 3n + 5 | O(n²) | n² outgrows everything else |
| n × m | O(n × m) | 2 independent inputs keep both letters |
| n + m | O(n + m) | either input can be the larger one |
Classifying real snippets
O(1). len reads a stored size and indexing jumps to a slot, so the function costs the same for 10 events as for 10 million.
O(1). It has a loop, but the loop runs exactly 7 times however long daily_counts is. A fixed number of iterations is constant work.
O(n + m). Building lookup walks yesterday once (m steps), then the loop does constant work per user in today (n steps). Check against yesterday directly in the if and it becomes O(n × m).
- Convert lookup lists to a set or dict before the loop
- Compute totals and maxes once, outside the loop that uses them
- Ask what happens to the step count when the input doubles
- Test with 10 times the sample size before shipping
- Use in on a list inside a loop over rows, or call the list's count or remove there
- Assume a one-line call costs a single step
- Read a loop over range(7) as O(n)
- Trust a 1,000-row test to predict a 50-million-row run
plays has n items and artists has m. What's the growth rate of top_artist?
Nesting with a fixed inner loop
n rows times 4 fields is 4n steps, so blank_fields is O(n). Replace the field list with a loop over rows and both counts become n, giving n × n: O(n²). Before multiplying, ask of every inner loop what it walks over.
This function has a loop inside a loop. How does its work grow with the number of rows?
> A nightly job joins 2 million app events to a 40,000-row device list, drops events from a blocklist of test accounts and removes duplicate event ids. On a 5,000-row sample it finished in under a second; on the full night's data it runs past its 06:00 deadline.
len and append, and none of them gets slower as data grows.x in some_list.Count how the steps in your code grow with the data, and catch the single line that turns minutes into days.
- Category
- Python
- Difficulty
- beginner
- Duration
- 28 minutes
- Challenges
- 15 hands-on challenges
Topics covered: Why Speed Matters, O(1) -- Constant Time, O(n) -- Linear Time, O(n²) -- Quadratic Time, Reading Complexity at a Glance
Lesson Sections
- Why Speed Matters
Most pipeline code is written against a sample: 1,000 rows pulled into memory, checked by eye, then shipped. The same code then meets the full table, perhaps 50 million rows, and a job that finished in 2 seconds is still running the next morning. The code is identical to what passed on the sample; the input grew, and the work the code does grew faster than the input did. Counting steps instead of seconds Growth is easier to reason about when you count a function's steps instead of timing it. Sec
- O(1) -- Constant Time
A constant-time operation costs the same number of steps whether the collection holds 10 items or 10 million. Python has several, and the 2 that matter most in pipeline code are reading a dict by key and checking whether a value is in a set. How a dict finds a key without searching Searching a list vs. checking a set This program searches a list of test accounts by hand, counting every comparison, then asks a set the same questions. The list search cost 1 check when the account sat at the front,
- O(n) -- Linear Time
A linear-time job visits each row once and does a fixed amount of work per visit, so 10 times the rows means 10 times the steps and no more. For a job that must read every record, that's the best growth rate on offer: no code can total revenue across 50 million orders without looking at all 50 million. A single pass with constant work per row Most pipeline code aggregates rows into a dict. Each play adds its seconds to its artist's running total. Watch the dict fill as the loop moves down the li
- O(n²) -- Quadratic Time
Quadratic code does work in proportion to n × n. Doubling the rows quadruples the steps, and 10 times the rows means 100 times the steps. It survives testing because sample data is small enough that even n × n steps finish quickly. A loop inside a loop The plainest quadratic shape is a loop whose body holds a second loop over the same input. For each of the n outer rows, the inner loop runs n times, so the innermost line runs n × n times. Going from 10 rows to 20 took the steps from 100 to 400.
- Reading Complexity at a Glance
Classifying code rarely takes an exact count. Find the part that grows fastest with the input and ignore the rest. A short set of rules covers most of what you will read in pipeline code. Rules for reading growth Why constants and small terms drop out Big O describes the shape of growth at large n, where only the biggest term matters. Take code that does n² + 3n + 5 steps. At n = 1,000,000 the n² term is 1,000,000,000,000, while 3n + 5 is about 3,000,000, less than a thousandth of a percent of t