Dynamic Arrays: What Happens When a Python List Runs Out of Room?
You can call append on a Python list a million times and it never says no. But memory can't stretch. So where does the room come from?
The short answer: when a list fills up, Python builds a bigger one somewhere else and moves everything over. That one fact explains why my_list[5] is instant while my_list.insert(0, x) gets slower the longer the list is.
In this post we build our own list class in Python, one method at a time, and see what each one costs. The video at the top covers the same ground with animations. This post adds a few things the video didn't have time for: what real Python does differently, and what all of this means for the code you write.
The Rule Behind Every Array
Memory is a long row of numbered cells. The number of a cell is its address.
An array takes a run of those cells, side by side, and uses them as slots. Think of it as a bookshelf mounted on that row:
- The shelf is the array
- The number of slots is its size
- The number of books on it is its length
- A slot's number is its index
- Where the shelf sits on the wall is its address
Everything in this post comes back to one rule:
The slots sit side by side.
That rule is why reading a slot is instant. It's also why inserting, removing and growing are slow. Keep it in mind as we go.
Step 1: The Shelf
A shelf needs three things: its slots, how many slots it has (size), and how many books are on it (length). The size is fixed when the shelf is built. The length changes with every book.
Python doesn't give us raw memory, so we fake the slots with a list of None values, where None means empty. To keep it honest, we never call that list's own append, insert or remove. We write those ourselves.
class Array:
def __init__(self, size):
self.__slots = [None] * size
self.__size = size
self.__length = 0
def is_full(self):
return self.__length == self.__size
def __str__(self):
items = ", ".join(str(x) for x in self.__slots)
return f"[{items}] (length: {self.__length}, size: {self.__size})"
The double underscores make the fields private, so code outside the class can't change them behind our back.
Step 2: Adding to the End
The next free slot always has the same number as the length. An empty shelf has length 0, so the first book goes in slot 0. With one book on the shelf, the next goes in slot 1.
So append puts the item at slots[length] and adds one to the length:
def append(self, item):
if self.is_full():
raise IndexError("The shelf is full")
self.__slots[self.__length] = item
self.__length += 1
This version gives up when the shelf is full. A real list doesn't, so the next step teaches it to grow.
Step 3: Growing When It's Full
Why not just add a slot at the end? Because the cells right after the shelf usually belong to something else. The shelf can't stretch into them.
So we build a bigger shelf somewhere else, copy every book across, and let go of the old one.
Finding room isn't always easy, either. Say memory has nine free cells and you need four. If those nine cells sit in three separate groups of three, none of them fits. Free isn't enough. The cells have to be side by side. The computer keeps looking until it finds a run that's long enough.
def __resize(self, new_size):
new_slots = [None] * new_size
for i in range(self.__length):
new_slots[i] = self.__slots[i]
self.__slots = new_slots
self.__size = new_size
def append(self, item):
if self.is_full():
self.__resize(max(1, self.__size * 2))
self.__slots[self.__length] = item
self.__length += 1
Why Double the Size?
Every resize copies every book, so it's expensive. The trick is to make it rare.
If the shelf grew by one slot at a time, every append would be a resize. Start with one slot and append 16 books: that's 120 books moved. Double the size instead and the same 16 appends move only 15 books. Most appends land in a free slot and cost one step. A resize happens only when the size hits 1, 2, 4, 8, 16, and so on.
Spread across all the appends, each one costs a small, fixed amount on average. That's why we say append is O(1) on average, even though a single append sometimes moves the whole list.
What Real Python Does
CPython (the standard Python) uses the same idea, with two differences:
- It grows by about an eighth, not double. On Python 3.14, a list's room goes 4, 8, 16, 24, 32, 40, 52, 64, 76 as you append. Smaller steps waste less memory, and the cost per append is still a fixed amount on average
- It tries to stretch first. Python asks the memory allocator to grow the block where it is. If the cells after it happen to be free, nothing moves. If they're taken, the data is copied to a new block, exactly like our shelf
You can watch the steps yourself: sys.getsizeof(my_list) jumps each time the list grows.
Reading a Slot: Instant
This is where the rule pays off.
To find slot 2, you don't search or count. The shelf starts at a known address, and every slot is the same size. So slot 2 is at start + 2 slots. That's one calculation whether the list holds four items or four million. In Big O terms, it's O(1).
def __getitem__(self, index):
if 0 <= index < self.__length:
return self.__slots[index]
raise IndexError("Index out of range")
def __setitem__(self, index, item):
if 0 <= index < self.__length:
self.__slots[index] = item
else:
raise IndexError("Index out of range")
Writing works the same way: jump to the slot and swap the item. The only check is that the slot is in use. Slot 9 on a three-book shelf is an IndexError.
But what if the items are different sizes? A Python list can hold a number, a long string and a dictionary side by side. The slots don't hold the objects themselves. Each slot holds a reference (the object's address), and every reference is the same size. So the math still works.
Searching: A Walk
Reading is instant when you know the slot. When you only know the item, there's no shortcut. The shelf has no idea where anything is, so index starts at slot 0 and checks each one. It returns the slot number when it finds a match, or -1 if it reaches the end.
def index(self, item):
for i in range(self.__length):
if self.__slots[i] == item:
return i
return -1
The loop stops at the length, not the size, because empty slots have nothing to check.
Twice the items means twice the checks. That's O(n).
Inserting in the Middle: A Shuffle
To put an item in slot 1, slot 1 has to be empty. So everything from slot 1 onward moves one slot to the right.
The order matters. Start from the left and slot 1's book lands on top of slot 2's, and that book is lost. So the loop starts from the right: the last book moves into the empty slot at the end, then the one before it, and so on until slot 1 is free.
def insert(self, index, item):
if index < 0 or index > self.__length:
raise IndexError("Index out of range")
if self.is_full():
self.__resize(max(1, self.__size * 2))
for i in range(self.__length, index, -1):
self.__slots[i] = self.__slots[i - 1]
self.__slots[index] = item
self.__length += 1
If the shelf is already full, it grows first, the same way append does.
The closer to the front you insert, the more items move. Inserting at slot 0 moves all of them. That's O(n).
Removing: The Same Shuffle, Backwards
remove first finds the item with the search we already wrote. Taking it out leaves a hole, and an array can't have holes, because the slots have to stay side by side. So everything after it moves one slot left. This time the loop starts from the left, so nothing gets overwritten.
Then the last slot, now a duplicate, is cleared, and the length drops by one. If the item isn't there, remove raises a ValueError, like Python's own list.
def remove(self, item):
index = self.index(item)
if index == -1:
raise ValueError(f"{item} is not on the shelf")
for i in range(index, self.__length - 1):
self.__slots[i] = self.__slots[i + 1]
self.__slots[self.__length - 1] = None
self.__length -= 1
Same cost as insert: the farther from the end, the more items move. O(n).
Try It Yourself
Here's the whole shelf, working. It's the same shelf and memory as in the video, it starts with two slots, and every method of the class has a button. Use the books, or type any data you like. The terminal underneath shows the Python call and what it returns. A few things to try:
- Append three books and watch the shelf grow from 2 to 4 slots. In memory, it can't stretch into 0xF2, so it moves to the first 4 free cells side by side, at 0xFF
- Keep going to 8 slots: the first 20 cells have no room left, so it has to look further
- Insert a book at slot 0 and count how many books slide
- Remove the first book, then the last one, and compare
- Click a slot number to read it, then try
shelf[9] - Search for a book that isn't there and watch it check every slot before it gives you
-1
An empty shelf with 2 slots at 0xF0. Pick a book or type anything, then call a method.
The Full Class
Here's everything together. Save it as shelf.py and run python3 -i shelf.py to try it in your terminal.
class Array:
def __init__(self, size):
self.__slots = [None] * size
self.__size = size
self.__length = 0
def is_full(self):
return self.__length == self.__size
def __resize(self, new_size):
new_slots = [None] * new_size
for i in range(self.__length):
new_slots[i] = self.__slots[i]
self.__slots = new_slots
self.__size = new_size
def append(self, item):
if self.is_full():
self.__resize(max(1, self.__size * 2))
self.__slots[self.__length] = item
self.__length += 1
def __getitem__(self, index):
if 0 <= index < self.__length:
return self.__slots[index]
raise IndexError("Index out of range")
def __setitem__(self, index, item):
if 0 <= index < self.__length:
self.__slots[index] = item
else:
raise IndexError("Index out of range")
def index(self, item):
for i in range(self.__length):
if self.__slots[i] == item:
return i
return -1
def insert(self, index, item):
if index < 0 or index > self.__length:
raise IndexError("Index out of range")
if self.is_full():
self.__resize(max(1, self.__size * 2))
for i in range(self.__length, index, -1):
self.__slots[i] = self.__slots[i - 1]
self.__slots[index] = item
self.__length += 1
def remove(self, item):
index = self.index(item)
if index == -1:
raise ValueError(f"{item} is not on the shelf")
for i in range(index, self.__length - 1):
self.__slots[i] = self.__slots[i + 1]
self.__slots[self.__length - 1] = None
self.__length -= 1
def __str__(self):
items = ", ".join(str(x) for x in self.__slots)
return f"[{items}] (length: {self.__length}, size: {self.__size})"
>>> shelf = Array(2)
>>> shelf.append("📕")
>>> shelf.append("📗")
>>> shelf.append("📘")
>>> print(shelf)
[📕, 📗, 📘, None] (length: 3, size: 4)
Summary
- Read or write a slot: O(1), instant. Start address + slot number
- Append: O(1) on average. Growing is rare because the size jumps ahead
- Grow: O(n). Every item is copied to the new block
- Search: O(n). Check slot by slot
- Insert or remove in the middle: O(n). Every item after it moves
Every row comes from the same rule: the slots sit side by side.
What This Means for Your Code
- Use
appendandmy_list[i]freely. They're the cheap operations - Be careful with
insert(0, x)andpop(0)inside a loop. Each call moves the whole list. If you keep adding or removing at the front, usecollections.deque, which is built for both ends - Searching a long list again and again is slow.
x in my_listandmy_list.index(x)walk the list like ourindexdoes. If you look things up a lot, asetor adictfinds them in one step on average
What's Next
Every slow operation here comes from keeping the slots side by side. So what if items could live anywhere in memory, and each one simply pointed to the next? Inserting would never shift anything, and growing would never mean moving everything.
But then how would you find slot 2 without counting from the start?
That's the next post: linked lists. See you there.
Connect with me: links.hamidouwb.com