Sub topic 8
The Dynamic Array Idea
This chapter assumes you can write loops and functions, know introductory Big-O notation, and have a rough picture of memory as numbered slots. It builds on the previous chapter, where a fixed-size array was shown to give O(1) indexing but no room to grow.
The problem to solve
A fixed-size array must be given its length when it is created. If you ask for 4 slots and later need a fifth value, the array cannot help you. The slots after it may already belong to other data, so it cannot simply extend in place.
Many programs do not know in advance how many items they will store. They read input, collect results, or build a list one item at a time. A dynamic array is a structure that lets you keep adding items without choosing a length up front.
The core idea
A dynamic array wraps an ordinary fixed-size array and adds bookkeeping. It keeps three things:
- A hidden fixed-size block of memory that holds the elements.
- A capacity, which is the number of slots in that block.
- A size, which is the number of slots currently in use.
Size is always less than or equal to capacity. The user sees only the first size slots. The remaining slots are spare room. When an append finds that size equals capacity, the structure allocates a larger block, copies the old elements into it, and uses the new block from then on.
A minimal implementation
class DynamicArray:
def __init__(self):
self._capacity = 1
self._size = 0
self._data = [None] * self._capacity
def __len__(self):
return self._size
def __getitem__(self, index):
if not 0 <= index < self._size:
raise IndexError("index out of range")
return self._data[index]
def append(self, value):
if self._size == self._capacity:
self._resize(2 * self._capacity)
self._data[self._size] = value
self._size += 1
def _resize(self, new_capacity):
new_data = [None] * new_capacity
for i in range(self._size):
new_data[i] = self._data[i]
self._data = new_data
self._capacity = new_capacityThree details matter here:
__len__returns the size, not the capacity. Callers never see the spare slots.__getitem__checks the index against_size. Index 3 may be a valid slot in the block, but if the size is 3, it holds no element.appendresizes before writing. The write then always has a free slot.
Tracing a few appends
Starting from an empty array with capacity 1:
| Append | Size before | Capacity before | Resize? | Capacity after |
|---|---|---|---|---|
| `"a"` | 0 | 1 | No | 1 |
| `"b"` | 1 | 1 | Yes, copy 1 element | 2 |
| `"c"` | 2 | 2 | Yes, copy 2 elements | 4 |
| `"d"` | 3 | 4 | No | 4 |
| `"e"` | 4 | 4 | Yes, copy 4 elements | 8 |
Most appends write one value and finish. A few appends do extra work to copy. The next chapters explain how often the copying happens and why it stays cheap on average.
Common mistakes
- Treating capacity as the length. Reading a slot between size and capacity returns
Nonein this code, or garbage in a language like C. - Forgetting to update
_dataand_capacitytogether in_resize. The two must always describe the same block. - Keeping a reference to the old block elsewhere. After a resize the old block is no longer the live storage.
Exercise
A dynamic array has size 8 and capacity 8. You append one element. What are the size and capacity afterward, and how many elements were copied during the resize, assuming the capacity doubles?
Show answer
The size is 9 and the capacity is 16. The append found the block full, so it allocated a block of 16 slots and copied all 8 existing elements before storing the new value.
Exercise
In the implementation above, why does __getitem__ compare the index with _size instead of _capacity?
Show answer
Slots from _size up to _capacity are spare room that holds no real element. Checking against _capacity would let a caller read a None placeholder as if it were data, so only indexes below _size are valid.