Arrays that grow: resizing by hand
A dynamic array grows by taking a block twice the size when it is full and copying the references across, so n appends copy fewer than 2n references in all: append is O(1) amortised.
Call list.append a million times and the list never knows in advance how long it will get. Underneath, its slots are a fixed-size block of contiguous memory; once it is full, the only way on is a bigger block and copying the old references across. If each new block were one slot bigger, a million appends would copy 0 + 1 + … + 999999, about 500 billion references. If each new block is twice as big, the total is under two million: fewer than 2 copies per append on average. In this lesson you write an array that grows, and do the sums.
Capacity and length
A growing array (a dynamic array) keeps two numbers:
- size: how many slots are in use, which is
len; - capacity: how many slots the block has.
While size < capacity, append puts the item in the next slot. When size == capacity, the memory right after the block may belong to another object, so the block cannot be lengthened in place. Instead: take a block twice as big, copy the old references across one by one, and point at the new block.
Names
d.dataObjects
In C you would free the old block yourself here; in Python it is reclaimed as soon as no reference points at it.
A DynArray has size = 3 and capacity = 4 and doubles when full. After two more appends, what are size and capacity?
Writing DynArray
Here [None] * capacity stands in for a fixed block of slots: it is only ever read and written by index, never appended to; growing is all done by hand.
1class DynArray:2 def __init__(self):3 self.capacity = 14 self.size = 05 self.data = [None] * self.capacity6 self.copies = 0 # copies made so far7 8 def append(self, x):9 if self.size == self.capacity: # full10 self._grow(2 * self.capacity)11 self.data[self.size] = x12 self.size += 113 14 def _grow(self, new_cap):15 new = [None] * new_cap16 for i in range(self.size):17 new[i] = self.data[i]18 self.copies += 119 self.data = new20 self.capacity = new_cap21 22 def __getitem__(self, i):23 if not 0 <= i < self.size:24 raise IndexError("index out of range")25 return self.data[i]26 27 def __len__(self):28 return self.size29 30d = DynArray()31for x in range(1, 10):32 d.append(x)33 print(x, "size =", len(d), "capacity =", d.capacity, "copies =", d.copies)34print(d[8], len(d))
1 size = 1 capacity = 1 copies = 0 2 size = 2 capacity = 2 copies = 1 3 size = 3 capacity = 4 copies = 3 4 size = 4 capacity = 4 copies = 3 5 size = 5 capacity = 8 copies = 7 6 size = 6 capacity = 8 copies = 7 7 size = 7 capacity = 8 copies = 7 8 size = 8 capacity = 8 copies = 7 9 size = 9 capacity = 16 copies = 15 9 9
__getitem__ and __len__ let you write d[8] and len(d) just as with a list. Note that __getitem__ checks the index against size, not capacity: the spare slots at the end do not count.
Here is the copying step inside _grow:
i1new = [None] * new_cap2for i in range(self.size):3 new[i] = self.data[i]4 self.copies += 15self.data = new6self.capacity = new_cap
With size = 5 and capacity = 8, what is d.data[6]? And d[6]?
None it was filled with. d[6] goes through __getitem__, which checks against size: 6 is not less than 5, so it raises IndexError. Empty slots belong to the capacity, not to what the array holds.Amortised: O(1) per append on average
Here is DynArray appending 9 times from capacity = 1, one line per append:
| Append no. | Capacity before | Switch? | Copied this time | Copied in all |
|---|---|---|---|---|
| 1 | 1 | no | 0 | 0 |
| 2 | 1 | to 2 | 1 | 1 |
| 3 | 2 | to 4 | 2 | 3 |
| 4 | 4 | no | 0 | 3 |
| 5 | 4 | to 8 | 4 | 7 |
| 6, 7, 8 | 8 | no | 0 | 7 |
| 9 | 8 | to 16 | 8 | 15 |
The total copied is 1 + 2 + 4 + … + p, where p, the capacity before the last switch, is less than n. That sum is 2p − 1, less than 2n. n appends do fewer than 3n things in all (n puts, plus under 2n copies), a constant per append on average: that is amortised O(1). One append on its own (the 9th copies 8) can be slow, but the slow ones get rarer and rarer.
What matters is growing in proportion. Grow by a fixed few slots each time and it is no longer cheap:
1def total_copies(n, grow):2 capacity, size, copies = 1, 0, 03 for _ in range(n):4 if size == capacity:5 copies += size # switching blocks copies all size items6 capacity = grow(capacity)7 size += 18 return copies9 10print("n", "+1 slot", "+10 slots", "double", sep="\t")11for n in [1000, 2000, 4000, 8000]:12 a = total_copies(n, lambda c: c + 1)13 b = total_copies(n, lambda c: c + 10)14 c = total_copies(n, lambda c: c * 2)15 print(n, a, b, c, sep="\t")
n +1 slot +10 slots double 1000 499500 49600 1023 2000 1999000 199200 2047 4000 7998000 798400 4095 8000 31996000 3196800 8191
When n doubles, the copies for +1 and +10 go up four times (O(n²)); the doubling column only doubles with n (O(n)).
| Growing when full | Copies for n appends | Per append on average |
|---|---|---|
| +1 slot each time | n(n − 1)/2 | O(n) |
| +10 slots each time | about n²/20 | O(n) |
| ×2 each time | under 2n | amortised O(1) |
| about ×1.125 each time (CPython's list) | roughly 8n | amortised O(1) |
This time capacity starts at 2. After 5 appends, what does it print?
1class DynArray:2 def __init__(self):3 self.capacity = 24 self.size = 05 self.data = [None] * 26 self.copies = 07 8 def append(self, x):9 if self.size == self.capacity:10 new = [None] * (2 * self.capacity)11 for i in range(self.size):12 new[i] = self.data[i]13 self.copies += 114 self.data = new15 self.capacity *= 216 self.data[self.size] = x17 self.size += 118 19d = DynArray()20for x in range(5):21 d.append(x)22print(d.capacity, d.copies)
In interviews: "Why is a dynamic array's append O(1)?" Say amortised: one resize is O(n), but n appends copy fewer than 2n items in all. Follow-up, "why not grow by 100 each time?": a fixed increment copies O(n²) in all. Follow-up, "when should it shrink?": halve it only when it is down to 1/4 full, not at 1/2, or alternating append and pop right at the boundary copies every time.
If, when full, it only adds 10 more slots each time (capacity += 10), what does each of n appends cost on average?
Starting from capacity = 1 and doubling when full, 17 values have been appended. What is the capacity now, and how many slots are empty?
Make it double
✓This DynArray grows by just 1 slot each time it is full and makes 36 copies. Make it double instead; and make __getitem__ check the index against size (raise IndexError past size), so the spare slots at the end cannot be read.
1 2 4 4 8 8 8 8 16 copied 15 times 9 out of range
1class DynArray:2 def __init__(self):3 self.capacity = 14 self.size = 05 self.data = [None]6 self.copies = 07 8 def append(self, x):9 if self.size == self.capacity:10 self._grow(self.capacity + 1)11 self.data[self.size] = x12 self.size += 113 14 def _grow(self, new_cap):15 new = [None] * new_cap16 for i in range(self.size):17 new[i] = self.data[i]18 self.copies += 119 self.data = new20 self.capacity = new_cap21 22 def __getitem__(self, i):23 return self.data[i]24 25d = DynArray()26caps = []27for x in range(1, 10):28 d.append(x)29 caps.append(d.capacity)30print(*caps)31print("copied", d.copies, "times")32try:33 print(d[8], d[9])34except IndexError:35 print(d[8], "out of range")
pop and shrinking
pop() from the end moves nobody: take out data[size - 1], set it to None, size goes down by 1: O(1). But append a million values and pop until only a few are left, and the million-slot block is still taking up memory. So a dynamic array shrinks too: when it is barely used, it switches to a smaller block and copies what is left across.
When to shrink takes some care. The obvious idea is "shrink to half when half full", but that goes wrong at the boundary: with capacity = 8 and size = 5, one pop leaves 4, exactly half, so it shrinks to 4 slots (4 copies); one append right after, the 4 slots are full again, so it grows back to 8 (4 more copies)… popping and appending back and forth at the boundary copies on every step.
pop(); append(x)4 copies every stepback and forth at the boundary, O(n) per steppop(); append(x)no copies at allstill amortised O(1)So the usual rule is shrink to half only when a quarter full: right after shrinking it is half full, so whether the next operation is an append or a pop, it takes many more steps to reach the next block switch.
Using the "shrink to half when a quarter full" rule, start at capacity = 16, size = 9 and pop 6 times in a row. What does it print?
1capacity, size = 16, 92caps = []3for _ in range(6):4 size -= 15 if capacity > 1 and size <= capacity // 4:6 capacity //= 27 caps.append(capacity)8print(caps)
pop, and shrinking
✓Finish pop(): take out the last item (setting its slot to None); then, if size has dropped to a quarter of capacity or less (and capacity > 1), shrink to half.
[16, 15, 14] 1 16 16 16 16 16 16 16 16 16 16 16 8 8 4 2 1
1class DynArray:2 def __init__(self):3 self.capacity = 14 self.size = 05 self.data = [None]6 7 def append(self, x):8 if self.size == self.capacity:9 self._resize(2 * self.capacity)10 self.data[self.size] = x11 self.size += 112 13 def _resize(self, new_cap):14 new = [None] * new_cap15 for i in range(self.size):16 new[i] = self.data[i]17 self.data = new18 self.capacity = new_cap19 20 def pop(self):21 # take data[size - 1], set it to None, size down by 1; shrink to half if too little is used22 return None23 24d = DynArray()25for x in range(1, 17):26 d.append(x)27popped = []28caps = []29for _ in range(16):30 popped.append(d.pop())31 caps.append(d.capacity)32print(popped[:3], popped[-1])33print(*caps)
How you write it at work
list is exactly such a dynamic array: when full it switches to a block bigger in proportion (CPython adds about 1/8 plus a few slots), so append is amortised O(1), and pop() shrinks it back when very little is used. You cannot see its capacity: the numbers from sys.getsizeof change between Python versions, so this course does not use it. You will not write DynArray at work; what to watch out for is making a new list every time round a loop:
1copies = 02a = []3for x in range(500):4 copies += len(a) + 1 # a + [x] makes a new list: everything copied again5 a = a + [x]6print(len(a), copies)7 8b = []9for x in range(500):10 b.append(x) # put in place: amortised O(1)11print(a == b)
500 125250 True
- One at a time:
a.append(x); a batch:a.extend(b)ora += b, which grows once, enough for all. a = a + [x]makes a new list each time, so n times round a loop copies n²/2 in all.- When you know the final length:
[0] * nor a list comprehension makes it in one go, skipping the resizes on the way. - Strings are the same:
s = s + cin a loop makes a new string each time; use"".join(parts).
Which of these, inside a loop, add up to O(n²) in total? You can pick more than one.
a = a + [x] and s = s + c make a new object every time and copy all of the old one, so n passes copy about n²/2 in all. a.append(x) and a += [x] both add in place and grow by a factor: amortised O(1).Summary
A dynamic array: when full, switch to a block twice the size
- size is how many slots are used, capacity how many there are
- When full: take a block twice as big, copy across, point at it; the old one is reclaimed once nothing refers to it
- n appends copy fewer than 2n items in all: amortised O(1)
- Growing by a fixed few slots copies O(n²) in all
- list.append grows in proportion like this; a = a + [x] in a loop is O(n²)
- pop shrinks to half only when a quarter full, so it never bounces between growing and shrinking at the boundary
1def append(self, x):2 if self.size == self.capacity:3 self._grow(2 * self.capacity)4 self.data[self.size] = x5 self.size += 1