Dynamic arrays
easy 16 minA dynamic array is an array that grows by itself.
Video lesson · Chapter 1 of 5
The fifth price tag
Dynamic arrays — The fifth lantern
1:25Reel
Read caption
Mavi moves four lanterns to make room for a fifth, separating length, capacity, and amortized append cost. One expensive move buys room for cheap appends.
How it works
Step through the idea, or press Play.
Keep spare capacity. The array reserves more slots than it uses, so most appends just write into the next free slot
Understand it
Start here
What a dynamic array is
A plain array is a fixed block of memory: you choose its length when you create it and it can never grow. A dynamic array wraps that block and grows or shrinks automatically. When it is full it allocates a larger block and copies the elements over. You keep the strengths of an array, access by index and contiguous memory, without having to know the size up front.
O(1) access by index
Element lives at . One calculation, one jump.
Amortised O(1) append
Most appends write one slot. The rare resize is paid for by all the cheap appends around it.
No size up front
Start with a few slots and let it grow as data arrives.
Cache friendly
Elements sit side by side, so the CPU reads them in fast, predictable runs.
The picture
Size versus capacity
Two numbers describe a dynamic array. Size is how many elements it holds. Capacity is how many slots it has allocated. The slots from size to capacity - 1 exist in memory but hold nothing yet; size is also the index where the next append will land.
| Slot | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Value | 10 | 20 | 30 | 40 | 50 | free | free | free |
How full is it?
- 1AppendWrite into the next free slot
- 2Full?size equals capacity
- 3GrowAllocate 2× and copy
- 4Keep appendingCheap again for a while
Each lap around the loop is twice as long as the last, so resizes get rarer as the array grows.
Under the hood
How append works
append(x)
class DynamicArray: def __init__(self): self.capacity = 1 self.size = 0 self.data = [None] * self.capacity 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_capacityarr = DynamicArray()for x in range(1, 10): arr.append(x) print(f"size={arr.size} capacity={arr.capacity}")Growth
The doubling strategy
When the array is full, double its capacity. It looks wasteful, but it is what makes append cheap on average. Capacities run , so reaching elements takes only about resizes.
_resize(new_capacity)
Number of resizes to reach n elements
Proof
Why append is amortised O(1)
Amortised cost is the total cost of a sequence of operations divided by the number of operations. One append can cost , but it cannot happen often. Count everything over appends starting from capacity 1.
Aggregate method
Accounting method: charge 3 credits per append
1 credit: write it
Pays for putting the new element in its slot.
1 credit: move itself
Saved on the element to pay for copying it at the next resize.
1 credit: move an elder
Pays to copy an older element that already spent its saved credit at an earlier resize.
Trade-offs
Choosing a growth factor
Total copies for growth factor r
| Language | Type | Growth | Note |
|---|---|---|---|
| Python (CPython) | list | about 1.125× | Plus a small constant; tight on memory, copies more often |
| Java | ArrayList | 1.5× | old + (old >> 1) |
| C++ | std::vector | 2× (GCC, Clang) or 1.5× (MSVC) | Implementation-defined |
| JavaScript | Array | Engine-specific | V8 grows by about 1.5× plus a constant |
| Go | slice | 2× for small, about 1.25× for large | Rule changes past a threshold |
| Rust | Vec | 2× | Amortised growth guaranteed |
Growing by a constant k is quadratic
Shrinking
Pop and the quarter rule
pop() removes the last element: decrement size, read the slot, clear it. Nothing moves, so it is . To give memory back, an array can also shrink, and the threshold matters.
pop()
Shrink at a quarter full
- After a shrink the array is half full: room to grow and to shrink.
- At least cheap operations come before the next resize.
- Pop stays amortised .
Shrink at half full
- A full array of 4: push grows it to 8, pop shrinks it back to 4.
- Alternating push and pop copies elements every time.
- This is called thrashing: per operation.
Middle edits
Insert and remove at an index
An array cannot hold gaps. Inserting at index shifts everything from onward one slot right, working back to front so nothing is overwritten. Removing at shifts everything after it one slot left, front to back.
insert(i, x) and remove_at(i)
Shifts per operation
Complexity
What each operation costs
| Operation | Typical | Worst | Amortised | Why |
|---|---|---|---|---|
get(i), set(i, x) | Address arithmetic | |||
append(x) | Occasional doubling copy | |||
pop() | Occasional shrink copy | |||
insert(i, x) | Shifts elements | |||
remove_at(i) | Shifts elements | |||
| search by value | Checks each element | |||
len() | Size is stored |
Static vs dynamic arrays
| Feature | Static array | Dynamic array |
|---|---|---|
| Size | Fixed at creation | Grows and shrinks |
| Memory | Exactly what you asked for | Some spare capacity |
| Append | Not possible once full | amortised |
| Access by index | ||
| Use when | Size known, every byte counts | Size unknown or changing |
In the wild
Watching a real list grow
CPython over-allocates a little on every grow. sys.getsizeof reports the bytes a list object reserves, so it jumps only when capacity changes, not on every append.
import sysitems = []last = sys.getsizeof(items)print(f"len=0 bytes={last}")for i in range(40): items.append(i) now = sys.getsizeof(items) if now != last: print(f"len={len(items):<3} bytes={now} (grew)") last = nowReserve up front
If you know the final size, preallocate:
[None] * nin Python,reserve(n)in C++,new ArrayList<>(n)in Java.Build, then join
Collect string pieces in a list and
''.join()once, instead of repeated+=that can copy each time.Stacks for free
appendandpop()at the end make a list a ready-made stack.
Pattern spotting
When to reach for a dynamic array
Which sequence structure?
Use a dynamic array when
- You build a list of unknown length.
- You need a stack: push and pop at the end.
- You collect results during a traversal or filter.
- Order matters and you read by index.
Pick something else when
- You add or remove at the front often (deque).
- You need first-in, first-out order (deque or queue).
- You test membership constantly (set).
- The size is fixed and memory is tight (static array).
Recap
Key takeaways
Key points
- A dynamic array is a fixed block plus a size and a capacity; it reallocates and copies when full.
- Doubling means about resizes and fewer than copies, so append is amortised and worst case .
- Any growth factor above 1 works; growing by a constant makes appends cost .
- Shrink at a quarter full and halve, never at half full, to avoid thrashing.
- Access, set,
lenandpop()are ; insert and remove in the middle are because of shifting. - Valid indexes run to
size - 1, never tocapacity - 1.