Lesson 3 of 3
What Python operations cost
Some single lines of Python are whole loops in disguise. Learn the price of everyday list, string, set and dict operations, why append is cheap on average, and how to price a function line by line.
Say which everyday Python operations take one step and which walk, shift or copy a whole list
Spot a hidden loop inside a loop and explain why it makes a function O(n2)
Explain why append is O(1) on average even though some appends copy every item
Price a function line by line and state its total cost in time and space
Replace a list lookup with a set to turn an O(n2) duplicate check into O(n)
Count the call stack when you state the space of a recursive function
The first lesson of this module found a repeated id by comparing every pair, which is O(n2). Module 0 did better with one walk and a set. Here is that same walk with a list as the notebook instead, the version many people write first, because a list is the container they reach for:
def has_duplicate(order_ids):
seen = []
for x in order_ids:
if x in seen:
return True
seen.append(x)
return False
One loop, so O(n)? The shape says so. But on 40,000 different ids, this lab's Python takes several seconds to run it. Make two small changes, [] to set() and append to add, and you have module 0's version, which finishes in milliseconds.
The difference is a loop you cannot see. x in seen looks like one step, but on a list it is a walk of its own. This lesson is a price list: which Python operations take one step, which ones walk, shift or copy a whole list, and how to add up the price of a function.
A reminder from the last two lessons, because we use these all the way through. O(n) means the work grows in step with n, the size of the input. O(1) means a fixed amount of work, whatever n is. O(n2) means the work grows with n times n, so doubling n multiplies it by 4.
A line can hide a loop
What does x in nums do when nums is a list? A list has no way to jump to a value. It can only compare items one at a time, from the left, until one matches or the list runs out. The trace below writes that walk out in Python. It adds a counter, checks, that the real in does not keep, so we can see the cost. Before you step through, guess how many comparisons each of the two calls makes.
def contains(nums, target):checks = 0for i in range(len(nums)):checks += 1if nums[i] == target:return Truereturn Falseprint(contains([4, 9, 2, 7], 9))print(contains([4, 9, 2, 7], 5))
(nothing printed yet)Python's in runs this same walk. It is written in C, so each comparison is fast, but it still compares one item at a time. As a frame card:
We price an operation by its worst case, as the first lesson of this module did, because we cannot count on the target sitting near the front. Several other built-ins walk a list the same way:
nums.index(x)walks until it findsxand returns its position:[4, 9, 2, 7].index(2)is 2. Ifxis missing, it compares every item and then raises aValueError. O(n).nums.count(x)(how many timesxappears),min(nums),max(nums)andsum(nums)always walk to the end, because any later item could change the answer: O(n).sorted(nums)costs more than one walk: O(n log n). Here log n is the base-2 logarithm from the first lesson, roughly how many times n halves before it reaches 1. For 100,000 items it is about 17, so a sort costs roughly 17 walks' worth of comparisons. Module 6 shows where that comes from.
nums = [6, 1, 8, 1, 5]. A program runs 8 in nums and then 3 in nums. How many comparisons do the two lookups make in total? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
One step, whatever the size
Which operations do not care how long the list is? An operation is O(1) when it goes straight to the right place instead of searching for it.
- Indexing,
nums[i], to read or to write. A list keeps its items in a row of equal-sized slots in memory, so Python finds slotiwith one multiplication and one addition: the start of the row plusitimes the slot size. Position 3 and position 30,000 cost the same. Module 3 draws the memory. len(nums). The list stores its own length and updates it on every change, so asking for it counts nothing.nums.append(x)andnums.pop().pop()with nothing in the parentheses removes the last item and hands it back. Both work at the end of the list, where nothing else has to move. Append has one catch, covered later in this lesson.- Set and dict lookups, adds and deletes. For a set that is
x in a_set,a_set.add(x)anda_set.remove(x); for a dict,d[key],key in d,d[key] = vanddel d[key](which deletes the key). A set or dict turns the key into a number, called its hash, and uses that number to jump to one spot in a table.
Set and dict operations are O(1) on average. That is the average case from the first lesson of this module: the cost on typical data. In a rare worst case, many keys land in the same spot and one lookup has to check them all, which is O(n). Module 3 builds the table and shows when that happens.
So the same question, x in ..., costs O(n) on a list and O(1) on average on a set. The program below measures the difference. It puts the numbers 0 to 19,999 in a list and in a set, then looks up 1,000 numbers that are in neither, which is the worst case for the list. Two notes on the code: the _ in 20_000 only makes the number easier to read, and time.perf_counter() reads a clock in seconds, so subtracting two readings gives the time in between. Before you run it, guess: will the list be 2 times slower than the set, 20 times, or more?
Shifts and copies
Which one-line operations move or copy many items? Two more kinds of hidden work look like one step: a shift moves every item from a spot to the end one slot over, and a copy duplicates every item it covers.
The front of a list
nums.insert(i, x) puts x at position i, and nums.pop(i) removes the item at position i and hands it back. At the front, nums.insert(0, x) looks like append at the other end. But a list keeps its items in slots that stay in order with no gaps, so making room at slot 0 means moving every item one slot to the right. The trace writes that out as a model: it adds one empty slot at the end, then moves the items right, one at a time. Guess first: how many items move to insert at the front of a 4-item list?
def insert_front(nums, x):moves = 0nums.append(None)i = len(nums) - 1while i > 0:nums[i] = nums[i - 1]moves += 1i -= 1nums[0] = xreturn moves
(nothing printed yet)So insert(0, x) costs one move per item: O(n). pop(0) is the mirror image: it removes slot 0 and shifts every remaining item one slot left, also O(n). In the middle of the list the shift is shorter. insert(i, x) moves the n − i items from position i to the end, and pop(i) moves the n − i − 1 items after position i. The end of the list is the one place where nothing moves.
Work at the end is cheap; work at the front is not. If you need to take items off the front again and again, collections.deque (a double-ended queue) removes from either end in O(1); module 5 covers it. Often the simpler fix is to remove nothing and walk with an index.
nums = [4, 7, 1, 9, 3, 8] has 6 items. How many of the existing items move one slot to the right when you run nums.insert(2, 5)?
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Slices and strings
A slice builds a new list and copies every item it covers into it. A reminder from module 1: nums[a:b] holds the items from position a up to, but not including, b, and nums[1:] runs from position 1 to the end. So nums[1:] on n items copies n − 1 of them: O(n), from one short expression. Once, that is fine. Inside a loop it adds up. The trace below sums a list by taking the first item and slicing off the rest, a shape you will meet in recursive code. Guess first: for a 4-item list, how many items get copied in all?
def total(nums):result = 0copied = 0while len(nums) > 0:result += nums[0]copied += len(nums) - 1nums = nums[1:]return result
(nothing printed yet)For n items the copies add up to (n − 1) + (n − 2) + ... + 0 = n(n − 1)/2. That is O(n2) for a loop that runs only n times. The fix is to walk without copying: for x in nums, or an index that moves forward.
Type exactly what this prints.
a = [1, 2, 3, 4]
b = a[1:]
b[0] = 9
print(a)
print(b)
Strings have the same cost, with a twist: a string can never be changed after it is made. (Module 1 called this immutable.) So s += "x" cannot add to s. It builds a new string, copies every character of s into it, then adds "x". A loop that adds one character at a time, n times, copies 0 + 1 + ... + (n − 1) characters: O(n2) in the worst case. CPython, the standard Python, can sometimes grow the string in place and skip the copy, but that is an optimization, not a promise, and Python's style guide (PEP 8) says not to rely on it.
The safe pattern: collect the pieces in a list and join them once. Each append is O(1), and ",".join(parts) copies every character exactly once, so the whole build is O(total length).
parts = []
for day in [12, 30, 7]:
parts.append(str(day))
line = ",".join(parts) # "12,30,7"
Put the lines in order to build initials(names), which returns the first letter of every name as one string: initials(["Ada", "Grace", "Linus"]) is "AGL". Use the fast pattern: collect the pieces in a list, then join once. Two of the lines do not belong.
Add lines from the list below, in order.
parts = []def initials(names):for name in names:return "".join(parts)result = ""result += name[0]parts.append(name[0])
Append is cheap on average
append writes at the end, so it should be O(1). But the row of slots behind a list has a fixed size. A list keeps a few spare slots, and when they run out, Python finds a bigger block of memory, copies every item across, and only then writes the new item. That one append costs n steps. So is append O(1) or O(n)?
The trace below is a model of a list that starts with room for one item and doubles its room whenever it fills up. It stores no items; it only counts. capacity is how many slots the block has, length is how many are in use, and copies is how many items have been moved to a bigger block. (The name _ is the usual name for a loop variable we never read.) Guess first: of 8 appends, how many copy anything?
def append_all(n):capacity = 1length = 0copies = 0for _ in range(n):if length == capacity:copies += lengthcapacity *= 2length += 1return copies
(nothing printed yet)Most appends copy nothing, and each copy is twice the size of the one before. The copies are 1, 2, 4 and so on, each smaller than n. A sum of doublings is always less than twice its last term (1 + 2 + 4 = 7, less than 2 × 4 = 8), so n appends copy fewer than 2n items in all. Add one write per append, and n appends cost fewer than 3n moves in total: fewer than 3 per append, on average.
That average over a long run of operations is called the amortized cost. One append can cost O(n), but n appends cost O(n) together, so we say append is amortized O(1). That is a stronger promise than the average case of a set, because it needs no luck with the data: any n appends, whatever the values, cost O(n) in total. Python's real lists double only while they are small: appending to an empty list gives it 4 slots, then 8, then 16. Once a list is long, each new block is only about an eighth bigger. That is still growth in proportion to the size, and that is all the argument needs. Module 3 shows the copy happen, slot by slot.
Use the model from the trace: room for 1 item at the start, and the room doubles whenever an append finds the list full. Over 16 appends, how many items get copied in total?
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Here is a recap of the hidden work so far, because it comes in only three kinds. Walks (in, index, count, min, max, sum on a list) visit every item. Shifts (insert and pop anywhere but the end) move the items between the spot and the end. Copies (slices, s += t, a full list growing) touch every item they copy. Everything that goes straight to a known place is O(1).
Pricing a whole function
How do you price a function you have never seen? Take each line, multiply its cost by the number of times it runs, and add. Then keep the biggest term, as in the last lesson. Here is the full price list, for a list nums of n items, a string s, a set and a dict:
| Operation | Cost | Why |
|---|---|---|
nums[i], nums[i] = x, len(nums) | O(1) | Goes straight to the slot, or reads a stored number |
nums.append(x), nums.pop() | O(1), append amortized | Works at the end; nothing moves |
x in nums, nums.index(x), nums.count(x) | O(n) | Walks the list |
min(nums), max(nums), sum(nums) | O(n) | Walks the list |
nums.insert(0, x), nums.pop(0) | O(n) | Shifts every item |
nums.insert(i, x), nums.pop(i) | O(n − i) | Shifts about n − i items |
nums[a:b] | O(b − a) | Copies the slice |
sorted(nums), nums.sort() | O(n log n) | Sorting (module 6) |
x in a_set, a_set.add(x), a_set.remove(x) | O(1) average | Jumps to one spot by hash |
d[key], d[key] = v, key in d, del d[key] | O(1) average | Jumps to one spot by hash |
s += t | O(len(s) + len(t)), worst case | Builds a new string |
"".join(parts) | O(total length) | Copies each character once |
Back to the duplicate check from the top of the lesson. Here it is priced line by line, for n different ids:
| Line | Cost each time | Runs | Total |
|---|---|---|---|
seen = [] | O(1) | once | O(1) |
for x in order_ids: | O(1) | n times | O(n) |
if x in seen: | O(len(seen)), up to n | n times | O(n2) |
seen.append(x) | O(1) amortized | n times | O(n) |
return True or return False | O(1) | once | O(1) |
The total is O(n2), and one line is responsible. Add the rows and keep the biggest term: O(1) + O(n) + O(n2) + O(n) + O(1) is O(n2). On 40,000 different ids, seen holds 0, then 1, then 2 ids, up to 39,999, so the in line makes 0 + 1 + ... + 39,999 = 799,980,000 comparisons, about 800 million. Work through a small case by hand first.
Trace the slow duplicate check by hand on [5, 3, 8, 1]:
def has_duplicate(nums):
seen = []
for x in nums:
if x in seen:
return True
seen.append(x)
return False
Make a table with one row per pass: x, what seen holds before the check, and how many comparisons x in seen makes. Then add up the comparisons.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
In real code the hidden loop comes with no warning. Find it in this one.
today and earlier are lists of customer names, each about n long. Which line makes this function O(n2)?
def new_customers(today, earlier):
result = []
for name in today:
if name not in earlier:
result.append(name)
return sorted(result)Choose one answer, then check.
Swap the list for a set, and the duplicate check drops to O(n). The walk stays the same; only the notebook changes, so the lookup line drops from O(n) to O(1) on average:
This duplicate check is correct but slow, because x in seen walks a list on every pass:
def has_duplicate(nums):
seen = []
for x in nums:
if x in seen:
return True
seen.append(x)
return False
Write has_duplicate(nums) so it runs in O(n) time: keep the same walk and change the notebook. It returns True if some value appears more than once, and False otherwise. The last test gives it 40,000 different numbers and a 1 second limit, which the list version cannot meet.
raise NotImplementedError, then press Run tests. Each check says what it expects.Recursion uses space too
Can a function use memory that grows with n without building a list? A function that calls itself is called recursive (module 8 teaches recursion properly). Every call that has started but not finished keeps its own box of names in memory. Those boxes pile up on the call stack: the calls still waiting for an answer, newest on top. Guess first: when sum_to(3) reaches its deepest point, how many calls are waiting at once?
def sum_to(n):if n == 0:return 0return n + sum_to(n - 1)
(nothing printed yet)So sum_to(n) keeps n + 1 boxes at its deepest: O(n) extra space, with no list anywhere in the code. A loop with one running total would need O(1). Python also limits how deep calls can go and raises RecursionError past the limit (about 1,000 nested calls by default in plain Python; this lab allows 5,000), so a recursion that goes one level per item fails on lists longer than the limit. When you state the space cost of a recursive solution, count the stack.
This function prints n, then n − 1, and so on down to 1, by calling itself. What extra space does count_down(n) use?
def count_down(n):
if n == 0:
return
print(n)
count_down(n - 1)Choose one answer, then check.
Last, say it out loud. The words you write here are the words you will use in the room.
An interviewer reads this function and asks: "What does it cost, and can you do better?"
def unique_in_order(tasks):
done = []
while len(tasks) > 0:
task = tasks.pop(0)
if task not in done:
done.append(task)
return done
Answer as you would in the room: price the lines that matter, give the total time and space, then say the fix and its cost.
Saved in this browser as you type.