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
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
This program searches a list of test accounts by hand, counting every comparison, then asks a set the same questions.
def search_list(items, target):
checks = 0
for item in items:
checks = checks + 1
if item == target:
break
return checks
test_accounts = ["qa_01", "qa_02", "qa_03", "qa_04", "qa_05", "qa_06"]
print(search_list(test_accounts, "qa_01"))
print(search_list(test_accounts, "qa_06"))
print(search_list(test_accounts, "u_777"))
test_set = set(test_accounts)
print("qa_06" in test_set)
print("u_777" in test_set)Output:
1 6 6 True False
The list search cost 1 check when the account sat at the front, and 6 for the last account or a missing one. With 600,000 test accounts, a miss would cost 600,000 comparisons. The set answered each question with a single hash calculation and would do the same with 600,000 accounts. A miss is the worst case for a list, because the loop must reach the end to be sure.
The table lists the operations you will use most and how each one's cost behaves as the collection grows.
| 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.
blocked = {"u3", "u9"}
artist_names = {"a1": "Nova", "a2": "Rook", "a3": "Ivy"}
plays = [["u1", "a2"], ["u3", "a1"], ["u4", "a3"], ["u9", "a2"], ["u4", "a1"]]
kept = []
for play in plays:
user = play[0]
if user in blocked:
continue
kept.append([user, artist_names[play[1]]])
print(kept)Output:
[['u1', 'Rook'], ['u4', 'Ivy'], ['u4', 'Nova']]
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?
- 'u5' in users
- users.remove('u5')
- 'u5' in user_set
- users.insert(0, 'u5')
About this lesson
This section is part of the Complexity: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.