Memory, and what Python's own operations cost
🌍 In real life. To remember a page in a book you can put in a bookmark (tiny, instant) or photocopy the whole chapter (a big pile of paper, and slow to make). Both let you come back to it, but they cost very different amounts of memory and time.
Programs have the same choice. So far we counted time (steps). Now two more questions: how much extra memory does a solution use, and what does each built-in Python operation really cost? A line can look tiny and still hide a loop.
The idea in one sentence: every solution costs time and memory, and many of Python's one-line operations hide a loop, so count both before you choose.
Its words:
- space complexity: Big-O for memory: how the extra memory grows with n (the input itself doesn't count)
- O(1) space: a few variables (a counter, a total), however big n is
- O(n) space: a new list or set the size of the input
- memory for time: spending extra memory to save steps, like the pair problem's set in lesson 33.1; one of the most common tricks in this whole course
What Python's operations cost (n is the length):
items[i],len(items),items.append(x),items.pop(): O(1)x in itemson a list: O(n), it checks item by itemx in son a set or a dict's keys: O(1) on average (Chapter 35 shows why)items.insert(0, x),items.pop(0): O(n), everything shifts (Chapter 34)items[a:b]: O(b - a), it copies;sorted(items): O(n log n)
See the difference grow. Looking a name up in a set stays at one step (O(1)), checking a list grows with n (O(n)), and sorting first costs O(n log n):
guests = ["Mina", "Rafi", "Tara", "Zara", "Adi", "Nila"]
invited = set(guests)
def count_list_checks(items, name):
checks = 0
for x in items:
checks += 1
if x == name:
break
return checks
print("list:", count_list_checks(guests, "Nila"), "checks")
print("set: ", "Nila" in invited, "in about 1 step")
first_three = guests[:3] # copies 3 items: a new list
first_three.append("Rina")
print(first_three, guests[:3])A hidden O(n²). This looks like one loop, but x in seen on a list is a second loop hiding inside it:
items = [3, 1, 3, 2, 1]
seen = []
for x in items:
if x not in seen: # O(n) each time!
seen.append(x)
print(seen)With a set instead of a list, the same idea becomes O(n). When code feels slow, look for loops hiding inside innocent-looking operations.
Mistakes and edge cases.
x in a_listinside a loop. The hidden O(n²) above. Keep the items you look up in a set or a dict.- Slicing in a loop.
rest = items[1:]copies n − 1 items; doing it on every step of a loop costs O(n²) in total. Move an index instead of slicing. pop(0)andinsert(0, x)in a loop. Each one shifts the whole list. A queue that takes from the front belongs incollections.deque(Chapter 40), where both ends are O(1).- Forgetting memory. A copy of a list of ten million numbers takes hundreds of megabytes. Saving time by keeping every copy can run the computer out of memory: count the space too.
Quiz
What is the time cost of
x in itemswhenitemsis a list of n things?- O(n)
- O(1)
- O(log n)
A function keeps only a running total and a counter, whatever the input size. How much extra memory does it use?
- O(1)
- O(n)
- O(n²)
What does this print?
a = [1, 2, 3, 4] b = a[1:3] b[0] = 99 print(a, b)Which loop is hiding an O(n²)?
- for x in items: if x not in seen_list: seen_list.append(x)
- for x in items: if x not in seen_set: seen_set.add(x)
- for x in items: total += x
The fast pair solution uses a set of everything it has seen. What did it trade?
- O(n) extra memory to get O(n) time instead of O(n²)
- Nothing: it is faster and uses no memory
- Correctness for speed
This keeps the first copy of each item and gives the right answer, but on 100,000 items it is far too slow. Which line makes it O(n²)?
def unique(items): seen = set() out = [] for x in items: if x not in out: seen.add(x) out.append(x) return out
Coding tasks
Write
has_duplicate(items)in O(n) time:Trueif any value appears twice. Use a set of the values seen so far.Fix the hidden O(n²):
unique_in_order(items)should give back each value once, in the order it first appears. Keep the order list, but check membership in a set.