What built-in operations cost: list, dict, set
Built-in operations can hide a loop: x in list compares one item at a time, O(n), while x in set is O(1) on average; insert(0) and pop(0) move the whole list, and slicing copies out a new list.
A website has 10,000 registered users, their names kept in a list. Each time someone new signs up, if name in users checks whether the name is taken. 10,000 sign-ups a day is 10,000 lookups; new names are mostly not taken, so each one compares against all 10,000 names: 100 million comparisons. Make users a set and the lookup line stays exactly the same, but each lookup compares about once. One line of Python can be a whole loop underneath; this lesson counts what the most common operations cost and ends with a cheat sheet.
x in list: one by one
A list knows nothing about the order of what is in it, so x in nums can only compare from the first element on, one by one, stopping when it finds x. Not finding it is the worst case: all n must be compared before it can say "not there". It does exactly what this hand-written function does:
i1def contains(nums, x):2 for i in range(len(nums)):3 if nums[i] == x:4 return True5 return False
nums.index(x), nums.count(x) and nums.remove(x) are the same: they all walk from the start, O(n).
nums is a long list. Which of these have to walk through it from the start? You can pick more than one.
in, count and remove all compare from the first element: count always goes to the end, in and remove stop when they find it but may have to go all the way. All O(n). nums[500] works out the position directly, and len(nums) is a number the list keeps: both O(1).x in set: work out the place, look only there
A set stores things differently. It keeps a row of slots, and to put x in it first computes from x which slot it belongs in (that computation is called hashing, hash(x)), and puts it there. To look x up it computes the slot again and looks only in that slot, ignoring all the others.
Here is a tiny hand-made "set": 1024 slots, an integer x goes in slot x % 1024. Compare it with a list: how many comparisons do 100 lookups take in each?
1nums = [i * 7 for i in range(1000)] # 1000 numbers: 0 7 14 … 69932queries = [i * 3 for i in range(100)] # 100 numbers to look up, some there, some not3 4def in_list(nums, x):5 compares = 06 for v in nums:7 compares += 18 if v == x:9 return True, compares10 return False, compares11 12SIZE = 102413table = [[] for _ in range(SIZE)]14for v in nums:15 table[v % SIZE].append(v) # into the slot where it belongs16 17def in_table(x):18 compares = 019 for v in table[x % SIZE]: # look only in x's slot20 compares += 121 if v == x:22 return True, compares23 return False, compares24 25found = total_list = total_table = 026for x in queries:27 ok, c = in_list(nums, x)28 found += ok29 total_list += c30 ok, c = in_table(x)31 total_table += c32print("found", found)33print("list:", total_list, "comparisons in all")34print("slots:", total_table, "comparisons in all")35s = set(nums)36print("a real set also finds", sum(1 for x in queries if x in s))
found 15 list: 85330 comparisons in all slots: 100 comparisons in all a real set also finds 15
The same 100 lookups: the list made over 80,000 comparisons, the slots just 100. Each lookup looks in one slot, and here no slot holds more than one number. Python's real set and dict work this way, only with more care over how slots are computed and how the row grows when it fills up.
6 in nums1000 comparisonsO(n): start to end6 in sabout 1 comparisonO(1) on average: one slotWhy "O(1) on average": if many values happen to land in the same slot, that slot has to be compared one by one. Python keeps more slots than elements (when the row is nearly full it moves to a bigger one), so a slot holds one or two on average. A dict is the same: d[key], key in d and d[key] = v are all O(1) on average. But v in d.values() looks for a value, and values are not stored by slot: that is O(n) again.
The same idea: four numbers go into 8 slots. What does it print?
1SIZE = 82table = [[] for _ in range(SIZE)]3for v in [5, 13, 6, 21]:4 table[v % SIZE].append(v)5print(table[5], table[6])
Drop duplicates, keep the order
✓dedupe(items) should drop duplicates, keeping the first time each item appears, in the original order. Searching the result list with x not in result would work too, but it makes n elements O(n²). Remember what you have seen in a set seen so it is O(n).
['b', 'a', 'c'] [3, 1, 2]
1def dedupe(items):2 seen = set()3 result = []4 for x in items:5 pass # not seen yet: add to seen, append to result6 return result7 8print(dedupe(["b", "a", "b", "c", "a"]))9print(dedupe([3, 1, 3, 3, 2, 1]))
Adding and removing at the front: things move
A list keeps its elements side by side in memory, index 0, 1, 2 … one after another. That is why nums[i] can compute the position directly, O(1). It is also the cost: take element 0 away and every element after it must move one place forward, or index 0 would be empty.
i1x = nums[0]2for i in range(1, len(nums)):3 nums[i - 1] = nums[i]4nums.pop() # the last place is left over
insert(0, x) is the reverse: everything moves back one place to make room at 0. Write a pop_front that counts, the way the figure does it, and empty a whole list from the front:
1def pop_front(nums):2 x = nums[0]3 moves = 04 for i in range(1, len(nums)):5 nums[i - 1] = nums[i]6 moves += 17 nums.pop()8 return x, moves9 10for n in [10, 100, 400]:11 nums = list(range(n))12 total = 013 while nums:14 x, moves = pop_front(nums)15 total += moves16 print(f"emptying {n:3} from the front: {total} moves")
emptying 10 from the front: 45 moves emptying 100 from the front: 4950 moves emptying 400 from the front: 79800 moves
And from the back? nums.pop() takes the last one and nothing in front of it moves: zero moves. So a list is fast as a stack (in and out at the end) and slow as a queue (in at the end, out at the front): taking out n means n(n − 1)/2 moves, O(n²).
| Operation | How many move | Cost |
|---|---|---|
nums.append(x), nums.pop() | 0 | O(1) |
nums.insert(0, x), nums.pop(0) | about n − 1 | O(n) |
nums.insert(i, x), nums.pop(i) | the n − i after i | O(n − i) |
In a list of 1000 elements, how many elements does nums.insert(990, x) shift one place to the right?
append at the very end moves nothing.Slicing copies
nums[i:j] makes a new list and copies the k = j − i elements into it one by one: O(k). The new list and the old one are two objects; changing one leaves the other alone.
After b = a[1:3], b[0] is changed. What does it print?
1a = [1, 2, 3, 4]2b = a[1:3]3b[0] = 94print(a, b)
[2, 3] and b points at it. Changing b[0] changes that new list; nobody touched a. Copying 2 elements is 2 steps: a slice costs as much as it is long.Copies are easiest to overlook inside loops and recursion. These two functions both compute a sum and both recurse 100 levels; one slices at every level, the other passes an index down:
1copied = 02 3def total_slice(nums):4 global copied5 if not nums:6 return 07 rest = nums[1:] # copies the n − 1 after the first8 copied += len(rest)9 return nums[0] + total_slice(rest)10 11def total_index(nums, i):12 if i == len(nums):13 return 014 return nums[i] + total_index(nums, i + 1)15 16nums = list(range(1, 101))17print(total_slice(nums), "copied", copied)18print(total_index(nums, 0), "copied none")
5050 copied 4950 5050 copied none
total_slice(nums[1:])4950 copiedO(n²)total_index(nums, i + 1)0 copiedO(n)Each pass does nums = nums[1:], and we add up how many elements get copied. What does it print?
1nums = list(range(10))2copied = 03while nums:4 nums = nums[1:]5 copied += len(nums)6print(copied)
Cost cheat sheet
Everything this chapter counted, in one place. The highlighted rows are one-liners that hide a loop: think twice before putting them inside one.
| Operation | Code | Cost |
|---|---|---|
| list: add or remove at the end | a.append(x), a.pop() | O(1) |
| list: read or write by index | a[i], a[i] = x | O(1) |
| length | len(a) | O(1) |
| list: add or remove at the front | a.insert(0, x), a.pop(0) | O(n) |
| list: search | x in a, a.index(x), a.count(x) | O(n) |
| slicing | a[i:j] | O(k), k = j − i |
| sorting | a.sort(), sorted(a) | O(n log n) |
| dict: read, write, key lookup | d[k], d[k] = v, k in d | O(1) on average |
| set: add, remove, lookup | s.add(x), s.discard(x), x in s | O(1) on average |
| dict: search the values | v in d.values() | O(n) |
In interviews: the most common way to lose points when asked for the complexity is missing these rows: an x in some_list, a list.pop(0) or a slice inside a loop multiplies the complexity by another n. The other way round, swapping a list for a set or dict, or pop(0) for deque.popleft(), is often exactly the optimisation the interviewer is waiting to hear.
Two sum
✓Find two numbers in nums that add up to target and return their indexes (i, j) with i < j. Two nested loops are O(n²); a dict from value to index needs only one pass: at nums[j], check whether target - nums[j] has been seen before.
(0, 1) (1, 2) None
1def two_sum(nums, target):2 where = {} # value -> its index3 for j in range(len(nums)):4 pass # is target - nums[j] in where? then record nums[j]5 return None6 7print(two_sum([2, 7, 11, 15], 9))8print(two_sum([3, 2, 4], 6))9print(two_sum([1, 2], 7))
How you write it at work
- Checking "is it there?" again and again: build
s = set(nums)first (O(n), once), then eachx in sis O(1) on average. Never writex in set(nums)inside a loop: it builds the set again every turn, slower than just searching the list. - Finding things by key, counting things: use a dict or
collections.Counter, not a search through a list. - Using it as a queue:
collections.deque. Adding and removing at both ends is O(1);popleft()moves nobody.
1from collections import deque2 3q = deque()4for task in ["download", "unpack", "install"]:5 q.append(task) # in at the right6q.appendleft("check network") # jump to the front, O(1)7while q:8 print(q.popleft()) # out at the left, O(1)
check network download unpack install
| list | deque | |
|---|---|---|
| add or remove at the end | O(1) | O(1) |
| add or remove at the front | O(n) | O(1) |
by index q[i] | O(1) | O(n) (it walks to the middle) |
A deque is not better everywhere: reading an element in the middle by index is slower. For reading by index, use a list; for in and out at both ends, a deque.
nums holds n numbers and queries holds m. What is this code in big O?
1for x in queries:2 if x in set(nums):3 hits += 1
set(nums) puts all n numbers into slots again on every pass, which is O(n); inside a loop of m passes that is O(m × n). Move s = set(nums) out of the loop so it happens once, and the whole thing becomes O(n + m).Counting off in a circle
✓n people (numbered 1 to n) stand in a circle and count off from person 1; whoever says k leaves, and the next person starts again from 1. Simulate it with a deque: move the first k − 1 people from the left end to the right end, then take the k-th off the left. Return the numbers in the order people leave.
[3, 6, 2, 7, 5, 1, 4] [2, 4, 1, 5, 3]
1from collections import deque2 3def josephus(n, k):4 q = deque(range(1, n + 1))5 out = []6 # while q: move k - 1 to the back, then take one away7 return out8 9print(josephus(7, 3))10print(josephus(5, 2))
Summary
Even one line has a cost
- x in list, index, count: compare from the start, O(n); x in set, k in dict: O(1) on average
- insert(0) and pop(0) move everything after: O(n); append and pop() are O(1)
- A slice copies out a new list: O(k); in recursion pass an index, not a slice
- Many lookups: set; find by key: dict; a queue: deque
- A crowded slot has to be compared one by one, which is why set and dict are O(1) "on average"
1s = set(nums) # O(n), once2x in s # O(1) on average3q = deque(); q.popleft() # O(1)4total(nums, i + 1) # pass an index, no slice
Chapter 0 quick check
5 questions: counting loops, log n, binary digits and the hidden cost of a list. Work out what each prints first, then pick an option.
The inner loop only goes up to i. What does it print for n = 5?
1n = 52steps = 03for i in range(n):4 for j in range(i):5 steps += 16print(steps)
i is tripled each time. What does it print?
1n = 1002steps = 03i = 14while i < n:5 i *= 36 steps += 17print(steps)
The outer loop runs n times, and each time the inner one halves j from n down to 1. What does it print for n = 8?
1n = 82steps = 03for i in range(n):4 j = n5 while j > 1:6 j //= 27 steps += 18print(steps)
sorted.How many binary digits do 1000 and 1024 have?
1print((1000).bit_length(), (1024).bit_length())1111101000). So binary search over 1000 numbers looks at most 10 times, over 1024 at most 11.Every pop(0) moves each element after the first forward one place, and the loop adds that count first. What does it print?
1nums = [1, 2, 3, 4, 5, 6]2moves = 03while nums:4 moves += len(nums) - 15 nums.pop(0)6print(moves)
deque.popleft() nothing moves.