Kodewick
Start learning →
What built-in operations cost: list, dict, set4 / 52

What built-in operations cost: list, dict, set

Lesson 4 of 52 · Part 1 · Getting started: how fast · about 20 minutes

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:

nums (find x = 6)492571012345↑i
1def contains(nums, x):2    for i in range(len(nums)):3        if nums[i] == x:4            return True5    return False

6 in nums: compare one by one from the start; not finding it means looking at all 6

nums.index(x), nums.count(x) and nums.remove(x) are the same: they all walk from the start, O(n).

Choose allPick all that apply

nums is a long list. Which of these have to walk through it from the start? You can pick more than one.

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?

main.py
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))
Output
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.

list6 in nums1000 comparisonsO(n): start to end
set6 in sabout 1 comparisonO(1) on average: one slot
Is 6 among 1000 numbers? The list compares one by one; the set works out the slot and looks only there

Why "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.

01234567

8 slots, x goes in slot x % 8: put in 3 11 4 19 in turn; values that land in the same slot line up there together
Guess the outputA wrong guess is fine

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])
Exercise 1

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).

It should print
['b', 'a', 'c']
[3, 1, 2]
exercise1.py
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]))
Output
Press Run or Ctrl+Enter

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.

nums24681001234↑i
1x = nums[0]2for i in range(1, len(nums)):3    nums[i - 1] = nums[i]4nums.pop()          # the last place is left over

What nums.pop(0) does inside: take the first away, then the 4 after it move forward one place each

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:

main.py
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")
Output
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²).

OperationHow many moveCost
nums.append(x), nums.pop()0O(1)
nums.insert(0, x), nums.pop(0)about n − 1O(n)
nums.insert(i, x), nums.pop(i)the n − i after iO(n − i)
Choose one

In a list of 1000 elements, how many elements does nums.insert(990, x) shift one place to the right?

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.

Guess the outputA wrong guess is fine

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)

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:

main.py
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")
Output
5050 copied 4950
5050 copied none
Slice at every leveltotal_slice(nums[1:])4950 copiedO(n²)
Pass an index downtotal_index(nums, i + 1)0 copiedO(n)
The same 100 levels of recursion: slicing at every level copies 99 + 98 + … + 0 = 4950, passing an index copies none
Guess the outputA wrong guess is fine

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.

OperationCodeCost
list: add or remove at the enda.append(x), a.pop()O(1)
list: read or write by indexa[i], a[i] = xO(1)
lengthlen(a)O(1)
list: add or remove at the fronta.insert(0, x), a.pop(0)O(n)
list: searchx in a, a.index(x), a.count(x)O(n)
slicinga[i:j]O(k), k = j − i
sortinga.sort(), sorted(a)O(n log n)
dict: read, write, key lookupd[k], d[k] = v, k in dO(1) on average
set: add, remove, lookups.add(x), s.discard(x), x in sO(1) on average
dict: search the valuesv in d.values()O(n)
What common list, dict and set operations cost (n is the number of elements)

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.

Exercise 2

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.

It should print
(0, 1)
(1, 2)
None
exercise2.py
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))
Output
Press Run or Ctrl+Enter

How you write it at work

  • Checking "is it there?" again and again: build s = set(nums) first (O(n), once), then each x in s is O(1) on average. Never write x 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.
main.py
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)
Output
check network
download
unpack
install
listdeque
add or remove at the endO(1)O(1)
add or remove at the frontO(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.

Choose one

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
Exercise 3

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.

It should print
[3, 6, 2, 7, 5, 1, 4]
[2, 4, 1, 5, 3]
exercise3.py
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))
Output
Press Run or Ctrl+Enter

Summary

Take-away

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.

Guess the outputA wrong guess is fine

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)
Guess the outputA wrong guess is fine

i is tripled each time. What does it print?

1n = 1002steps = 03i = 14while i < n:5    i *= 36    steps += 17print(steps)
Guess the outputA wrong guess is fine

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)
Guess the outputA wrong guess is fine

How many binary digits do 1000 and 1024 have?

1print((1000).bit_length(), (1024).bit_length())
Guess the outputA wrong guess is fine

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)