iq.lab
Python starts when a code cell comes near or you run one
03 Arrays and hash maps

Lesson 1 of 5

How a list really works

A Python list is a block of numbered slots in memory with its items side by side. That one picture explains why reading any index takes one step, why append is cheap on average, why the front of a list is expensive, and how to build a grid that behaves.

About 1 hour 20 minutes
By the end you can
  • Work out where nums[i] lives from the start address and the slot size, and say why reading it is O(1)

  • Explain length, capacity and spare room, and why append is amortized O(1)

  • Count the moves an insert or a pop makes at any position

  • Rotate a list with slices and state the cost in time and space

  • Build a grid with a comprehension and read grid[r][c]

A pipeline hands you a list of a million event ids. The last one, events[999_999], comes back as fast as the first, events[0]. (The _ inside a number is only there to make it easier to read.) events.append(x) is almost always instant. events.insert(0, x) moves a million items before it finishes.

Same list, very different prices. Module 2 gave you those prices as a table. This lesson opens the list up and shows where each price comes from. A list is a row of slots in memory, and almost every list cost you will quote in an interview follows from that one picture. It is also the picture the next lesson builds on: a hash map is a list of buckets with a clever way to pick the bucket.

Memory is a row of numbered slots

What does Python do when you write nums[3]? Start with memory. The computer's memory is one long row of bytes, and each byte has a number, called its address. (A byte is the smallest piece of memory with its own address; it holds one small number, 0 to 255.) Give the processor an address and it reads what is stored there directly, without looking at anything else first.

A list reserves one block of memory and keeps its items side by side in it, in order: nums[0] in the first slot, nums[1] in the next, and so on, with no gaps. Every slot is the same size: 8 bytes on a 64-bit machine, which is what most laptops and servers are. So if the block starts at address 1000, slot 1 starts at 1008, slot 2 at 1016, and in general:

address of nums[i] = start + i × 8

That is one multiplication and one addition, whatever i is. Python does not walk to position 3; it computes where position 3 is and goes there. Reading nums[3] and reading nums[999_999] cost the same, which is what O(1) means: a fixed amount of work that does not grow with the list. (The addresses in this lesson are small made-up numbers. Real ones are much longer, but the arithmetic is the same.)

How can every slot be 8 bytes when one item is 7 and another is a long string? Each slot holds a reference: the address of the value, which lives elsewhere in memory. A reference has the same size whatever it points at. That is how one list can hold values of any size and still use the arithmetic.

The trace below writes the address rule as a function and uses it for two positions. Before you step, guess: does the call for position 4 run more lines than the call for position 0?

Step throughFinding a slot by arithmetic
Step 1 of 12
Line 1 is about to run.
def address_of(start, i):
return start + i * 8
nums = [12, 30, 7, 25, 18]
for i in [0, 4]:
print(i, address_of(1000, i), nums[i])
Names
no names yet
Output
(nothing printed yet)
Work it outWhich slot is it?

A list's block starts at address 1000, and every slot is 8 bytes. To read nums[i], Python goes to address 1056. What is i? Type a whole number.

i

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Spare room, and what happens when it runs out

append adds an item at the end. A block keeps the size it was reserved with, so where does the new item go? A list can reserve more slots than it holds items, and two numbers describe that:

  • Length is how many items the list holds. It is what len(nums) returns.
  • Capacity is how many slots its block has. The slots past the last item are spare room: reserved for the list, but not part of it yet.

An append into spare room writes one slot and moves nothing. When there is no spare room, the list needs a bigger block, and the memory right after its block may already be in use. So in general the list moves: Python reserves a new, bigger block, copies every item across, writes the new item, and gives the old block back.

The figure below shows a list of five items in a block of eight slots. Under each slot are its position and its address. A move is one item copied or shifted from one slot to another, and the readouts count them. Before you press anything, guess: of the next four appends, which ones move items, and how many?

The same mechanism in Python code: a list named block stands for the block of slots, with None in the spare ones, and length counts the items in use. The arrow length points at the first spare slot. Guess first: how many items does each of the two appends move?

Step throughAppend into a block that can fill up
Step 1 of 26
Line 1 is about to run.
def append(block, length, x):
if length == len(block):
bigger = [None] * (2 * len(block))
for k in range(length):
bigger[k] = block[k]
block = bigger
block[length] = x
return block, length + 1
block = [12, 30, 7, None]
length = 3
block, length = append(block, length, 25)
block, length = append(block, length, 18)
print(block, length)
Names
no names yet
Output
(nothing printed yet)

So is append O(1) or O(n)? One append can copy every item. But the new block doubles the room, so each big copy is followed by many free appends. In the figure, the copy of 8 items bought 7 free appends, and the next copy would move 16 items and buy 15. Count from the start: 4 appends cost 8 moves, and 12 appends cost 8 + 16 = 24 moves. Both come to 2 moves per append on average. The pattern holds as the list grows: each copy moves 2 items for every append since the copy before it (16 moves for appends 5 to 12, which is 8 appends), so in this figure the average never climbs above 2.

An average over a long run of operations is the amortized cost, so append is amortized O(1). Module 2 introduced the term; now you have seen the copies it averages. CPython, the standard Python, grows a long list by about an eighth of its size each time instead of doubling it, so it copies more often, but each growth is still in proportion to the list's size, and that is all the argument needs.

On paperSix appends on paper

The append trace started with 3 items in a block of 4 slots. On paper, append 6 more items, one at a time. For each append write three numbers: the length after it, the capacity after it, and the moves it made. Use the figure's rule: a full block moves to a new block with double the room, one move per item copied. Writing the new item is not a move.

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.

Total moves for the 6 appends

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

So far: a list is a block of slots. Reading any index is arithmetic, O(1). Length counts items, capacity counts slots, and the spare slots make most appends free. A full list moves to a bigger block, and doubling keeps the average cost of append constant.

The front of the list

What does nums.insert(0, x) cost? Slot 0 is taken, and the promise says no gaps, in order. So to free slot 0, every item has to move one slot to the right. The moves must start from the end: moving the first item right would write over the second before it had moved.

The figure below starts with the same five items. Guess before you press: how many moves does Insert at front make, and how many does Pop make?

Work at the end of a list is cheap, and work at the front moves everything. The middle is in between. Here is an insert at any position i, written out on the block the append trace ended with. It assumes the block has a spare slot, as this one does; a full block would first move to a bigger one, as append does. Guess first: inserting at position 2 of five items, how many items move?

Step throughInsert at position i
Step 1 of 19
Line 1 is about to run.
def insert(block, length, i, x):
j = length
while j > i:
block[j] = block[j - 1]
j -= 1
block[i] = x
return length + 1
block = [12, 30, 7, 25, 18, None, None, None]
length = insert(block, 5, 2, 40)
print(block, length)
Names
no names yet
Output
(nothing printed yet)

Insert at position i moves the items from i to the end: n − i of them, for a list of n items. At the front, i is 0, so all n move: O(n). At the end, i is n, so none move, which is why append is the cheap case. pop(i) is the mirror image: it closes the hole by moving the n − i − 1 items after position i one slot left. So pop(0) moves n − 1 items, and pop() from the end moves none.

Work it outInsert at the front of six

A list holds 6 items in a block with spare room. How many moves does nums.insert(0, x) make? A move is one item shifted from one slot to another; writing x into slot 0 is not a move.

moves

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

A pop in the middle follows the mirror rule. Count with care:

Work it outPop from the middle

nums is [4, 8, 15, 16, 23, 42]. How many moves does nums.pop(1) make? A move is one item shifted from one slot to another; taking the 8 out is not a move.

moves

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

A front insert costs one line of code, so it hides well inside a loop. Price this one:

Quick checkNewest first

This function returns the events newest first:

def newest_first(events):
    out = []
    for e in events:
        out.insert(0, e)
    return out

What does it cost for a list of n events?

Choose one answer, then check.

If a program needs to add and remove at the front again and again, collections.deque (a double-ended queue, module 5) does both ends in O(1). Often the simpler fix is the one in that exercise: work at the end, then reverse once.

Rotating a list

Rotation is a classic interview task, and the prices from this lesson decide between its two answers. Rotating a list right by k steps moves every item k slots to the right, and the items pushed off the end wrap around to the front. [10, 20, 30, 40, 50] rotated by 2 is [40, 50, 10, 20, 30].

The first idea: rotate by one step, k times. One step is a pop() from the end (free) and an insert(0, ...) at the front (every other item shifts). The trace counts the shifts in a name shifts that Python itself does not keep. Guess first: how many shifts for k = 2 on five items?

Step throughRotating one step at a time
Step 1 of 14
Line 1 is about to run.
def rotate_by_steps(nums, k):
shifts = 0
for _ in range(k):
last = nums.pop()
nums.insert(0, last)
shifts += len(nums) - 1
return shifts
Names
no names yet
Output
(nothing printed yet)

Each step shifts n − 1 items, so k steps make k(n − 1) moves: O(nk). For n = 100,000 and k = 50,000 that is 50,000 × 99,999, about 5 billion moves. Rotating by n steps puts every item back where it started, so only k % n steps matter (% is the remainder after division). That trims k, but k % n can still be close to n.

The better idea builds the answer in one go: the last k items, followed by the first n − k items. Both pieces are slices. (A reminder from module 1: nums[a:b] is a new list of the items from position a up to, but not including, b. Leave out a to start at 0, or b to run to the end.) Try the pieces by hand first:

PredictTwo slices

Type exactly what this prints, one value per line.

nums = [10, 20, 30, 40, 50]
k = 2
cut = len(nums) - k
print(cut)
print(nums[cut:])
print(nums[:cut])
print(nums[cut:] + nums[:cut])

Now write it. Like sorted, your function returns a new list and leaves the original alone.

Code itRotate with slices

Write rotated(nums, k), which returns a new list: nums rotated right by k steps. nums itself must not change. k is 0 or more and can be larger than the length, and nums can be empty (then return []). Use slices, not a loop of insert calls. Then press Watch it run.

⌘+Enter runsPython starts when a code cell comes near or you run one
Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

What did the slices cost? Each slice copies the items it covers, so the two slices copy n items between them, and + copies them once more into the result: about 2n copies, O(n) time. The price is space: the slices and the result are new lists, O(n) extra.

LeetCode's version of this task (Rotate Array, number 189) asks you to change the caller's list in place, and its follow-up asks for O(1) extra space. Writing nums[:] = ... puts the result into the caller's list, but the slices still build an O(n) copy first. The in-place version is in the practice bank as Rotate a list; try it after this lesson.

Lists of lists

A board, an image or a table of distances is a grid: rows and columns. In Python a grid is a list whose items are lists, one list per row. grid[r][c] reads row r, column c. len(grid) is the number of rows, and len(grid[0]), the length of row 0, is the number of columns.

grid[r][c] is two O(1) reads, not one. The outer list's slots hold references to the row lists. grid[r] follows slot r to row r, and [c] then reads slot c of that row. A row you get out of the grid is the row itself, not a copy, so a change made through it shows up in the grid.

The trace builds a grid of two rows and three columns with a list comprehension: a loop written inside brackets, which runs the part before for once per pass and collects the results in a new list. [0] * 3 is the list [0, 0, 0]. Then the trace changes one cell, takes out a row and changes it. Before you step, guess what the last line prints.

Step throughA grid is a list of rows
Step 1 of 8
Line 1 is about to run.
Build a new row of three zeros on each of two passes.
grid = [[0] * 3 for _ in range(2)]
grid[1][2] = 7
row = grid[1]
row[0] = 4
print(grid)
Names
no names yet
Output
(nothing printed yet)
PredictA row taken out of a grid

Type exactly what this prints, one line per print.

grid = [[1, 2, 3], [4, 5, 6]]
row = grid[0]
row[2] = 9
print(grid[0][2], grid[1][2])
print(len(grid), len(grid[0]))

Build each row on its own pass, as the comprehension does. The tempting shortcut [[0] * 3] * 2 repeats what the outer list holds, and what it holds is a reference. So it makes two slots that point at one row, and a change to grid[0][1] shows up in both rows. This is the shared-row bug from module 1, and now you can see why it happens: * 2 copies references, not rows.

Then why is [0] * 3 safe? It also repeats one reference, to the number 0. But row[1] = 5 does not change that 0: it points slot 1 at a different value, 5. A number cannot be changed in place, so sharing it is harmless. A row can be, so sharing a row is a bug.

Put in orderA grid with separate rows

Put the lines in order to build make_grid(rows, cols, fill), which returns a grid of rows rows and cols columns with fill in every cell, where every row is its own list. Indentation is part of each line. Two of the lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • return grid
    • row = [fill] * cols
    • return [[fill] * cols] * rows
    • def make_grid(rows, cols, fill):
    • row = [fill] * cols
    • grid = []
    • for _ in range(rows):
    • grid.append(row)

    Reading a grid by its row and column indexes, in an order other than row by row, is a loop skill of its own. The practice bank has one such walk: Spiral order reads grid[r][c] ring by ring, with four bounds that move inward, and every bound is a chance for an off-by-one. Try it after this lesson.

    Last, say it out loud. The words you write here are the words you will use in the room.

    Say itSay it like you would in the room

    An interviewer asks you to rotate a list right by k steps. Before typing, say: a brute force and its cost, a better approach and its cost, and the edge cases you would check. Write it in a few plain sentences.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: How a hash map works