Sub topic 9
Tracking size and capacity
This chapter assumes you know basic Python (classes, loops, methods) and introductory Big-O notation. It also assumes you know that an array occupies one contiguous block of memory. The chapter explains why a dynamic array needs two numbers instead of one, and how the code keeps them consistent.
Two numbers, two meanings
A fixed-size array has one length, and that length is also the size of its memory block. A dynamic array separates these two ideas:
- Size is the number of elements the user has stored. It is what
len()reports. - Capacity is the number of slots in the underlying block. It is always at least the size.
The slots from index size up to capacity - 1 are allocated but unused. They are spare room, so that an append does not need a new block every time.
| Term | Meaning | Changes when |
|---|---|---|
| size | Elements the user has stored | append, insert, pop |
| capacity | Slots in the memory block | the array resizes |
The invariant
Every method must preserve this rule:
0 <= size <= capacity
Valid elements live in indexes 0 to size - 1. Everything after that is spare. Methods that read must check against size, not capacity. Methods that write at the end must check against capacity before writing.
How the code tracks them
Here is the class from the plan. Look at where each number is read and written.
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_capacityNotice these points:
__len__returns_size. Capacity is internal and never exposed throughlen().__getitem__checks the index against_size. If it checked_capacity, an index such as 3 in an array of size 2 and capacity 4 would returnNone, a spare slot, instead of raising an error.appendcompares_sizeto_capacity. When they are equal the block is full, so it resizes first._resizechanges only the block and_capacity. It leaves_sizealone, because resizing adds no elements.appendwrites at index_size, the first spare slot, then increments_size.
Tracing the numbers
Starting from an empty array and appending four values gives this sequence:
| After append of | Size | Capacity | Resized? |
|---|---|---|---|
| first value | 1 | 1 | No, the initial slot was free |
| second value | 2 | 2 | Yes, 1 to 2 |
| third value | 3 | 4 | Yes, 2 to 4 |
| fourth value | 4 | 4 | No, one spare slot was used |
You can confirm this by running the class and printing the private fields:
arr = DynamicArray()
for value in [10, 20, 30, 40]:
arr.append(value)
print(len(arr), arr._capacity)The output is 1 1, 2 2, 3 4, 4 4.
Common errors
- Checking capacity in reads. This exposes spare slots as if they were data.
- Updating capacity without replacing the block. The two then disagree, and a later write goes out of range.
- Forgetting to clear a slot after removal.
popsets the vacated slot toNone, so the array does not keep a reference to an object the user thinks is gone.
Exercise
A DynamicArray has size 3 and capacity 8. You call arr[5]. What happens, and why does the code give that result?
Show answer
It raises IndexError. Slot 5 exists in the memory block because the capacity is 8, but _getitem_ checks the index against size (3), not capacity. Slots 3 to 7 are spare and not valid elements.