Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
A fixed array never gets longer. A dynamic array fills its box, then copies everything into a box twice the size. Build one for Emma's playlist in Python, count the copies and shifts, and see why adding at the end stays cheap while inserting at the front costs almost 50 million shifts for 10,000 songs.
What you will learn
- Explain why any slot in an array is one jump away
- Build a dynamic array in Python that doubles when it is full
- Explain why doubling keeps adding at the end cheap
- Count the shifts an insert at the front or middle costs
Before you start
- Python classes and lists
- Big-O basics
A dynamic array is a list that grows. The idea is simple: add until the box is full, get a box twice the size, and copy everything across. It's hiding inside almost every app you use, and you'll see exactly why it's fast in some places and slow in others.
A playlist that keeps growing
Emma has a playlist of five songs, Sunny, Rain, Stars, Waves and Night, and every week she adds more. Imagine her list has only two slots, say [None] * 2. Sunny and Rain fit, but there's no slot for Stars. A fixed array never gets bigger.
So you'll build a playlist that grows. Two songs, two slots. Add a third song, and now there are four slots.
An egg box that grows
Picture an egg box with two slots, both holding an egg. The box is full. One more egg comes, so you get a box twice the size, move the two eggs across, and the new egg goes in. Full again? Twice the size again, eight slots, and you move all four eggs. Two, four, eight, sixteen. The box doubles, so moving happens rarely.
There's something nice about an egg box. All the slots are the same size, side by side, with no gaps. So the sixth slot is exactly five slots along from the start, and you jump straight to it instead of counting your way there. That's just as true for a box of a million slots. (How memory works explains why.)
Now the other case. Squeeze an egg into the middle, and every egg after it has to slide one slot along. The more eggs, the more sliding.
The main script
from playlist import Playlist
from bigger_box import BiggerBox
emma = Playlist()
songs = ["Sunny", "Rain", "Stars", "Waves", "Night"]
for song in songs:
emma.add(song)
print(f"{song}: size {emma.size}, slots {len(emma.slots)}")
print("copies: " + str(BiggerBox.copies))
emma.insert(1, "Jazz")
print("insert Jazz at 1: shifts = " + str(Playlist.shifts))
Sunny: size 1, slots 2
Rain: size 2, slots 2
Stars: size 3, slots 4
Waves: size 4, slots 4
Night: size 5, slots 8
copies: 6
insert Jazz at 1: shifts = 4
The slots go two, four, eight. And inserting Jazz slid four songs.
Inside Playlist and BiggerBox
from bigger_box import BiggerBox
class Playlist:
shifts = 0
def __init__(self):
self.slots = [None] * 2
self.size = 0
# put the song in the next free slot
def add(self, song):
if self.size == len(self.slots):
self.slots = BiggerBox.twice(self.slots)
self.slots[self.size] = song
self.size += 1
# slide every song after index one slot to the right
def insert(self, index, song):
if self.size == len(self.slots):
self.slots = BiggerBox.twice(self.slots)
for i in range(self.size, index, -1):
self.slots[i] = self.slots[i - 1]
Playlist.shifts += 1
self.slots[index] = song
self.size += 1
slots is the box, a plain list with two slots to start, and size is how many songs are in it. In add, if size == len(self.slots) the box is full, so you first get a bigger box. Then the song goes into the next free slot, slots[size], and size goes up by one.
insert must make room first. Its loop slides every song after the index one slot to the right, counting each slide in shifts.
class BiggerBox:
copies = 0
# a box twice the size, then copy every song across
@staticmethod
def twice(old):
bigger = [None] * (len(old) * 2)
for i in range(len(old)):
bigger[i] = old[i]
BiggerBox.copies += 1
return bigger
twice makes a new list of len(old) * 2 slots, copies every song across one by one, and hands the bigger box back. Why all this work? Because an array can never get longer. So you make a new one, and copy.
Why twice the size, not one more?
Say you grow by one slot each time. The box is full, so you add one slot and move every song. The very next song fills it, so you do it again, and again. For 100,000 songs that's almost 100,000 grows and close to five billion songs moved.
Doubling gives room for a whole lot more songs before the next grow. For 100,000 songs that's only 16 grows and about 131,000 songs moved. A big jump in size makes the grows rare, and that's the whole trick.
Insert in the middle: 4 shifts
Jazz wants index 1, but Rain is sitting there. Five songs, eight slots, so no bigger box this time. The songs sit side by side with no gaps, so every song after index 1 must move over.
Adding at the end needs zero shifts. Inserting at index 1 needs four, one for every song after it. The worst case is index 0, where every song slides.
Grow the playlist
grow_app.py adds n songs at the end of one playlist and inserts n songs at index 0 of another:
from playlist import Playlist
from bigger_box import BiggerBox
fmt = "{:7,d} songs: end {:7,d} copies, front{:11,d} shifts"
for n in (100, 1_000, 10_000):
BiggerBox.copies = 0
end = Playlist()
for i in range(n):
end.add("song")
copies = BiggerBox.copies
Playlist.shifts = 0
front = Playlist()
for i in range(n):
front.insert(0, "song")
print(fmt.format(n, copies, Playlist.shifts))
100 songs: end 126 copies, front 4,950 shifts
1,000 songs: end 1,022 copies, front 499,500 shifts
10,000 songs: end 16,382 copies, front 49,995,000 shifts
Ten thousand songs: about sixteen thousand copies at the end, against almost fifty million shifts at the front. Ten times the songs meant about sixteen times the copies (the box happened to just double past 8,192), but a hundred times the shifts.
Read the cost off the code
| Operation | Cost | Why |
|---|---|---|
| Reach any slot by index | O(1) | equal slots side by side, one jump |
| Add at the end | O(1) on average | next free slot; doubling makes grows rare |
| Grow when full | O(n), but rare | copy every song to a box twice the size |
| Insert at the front or middle | O(n) | every song after the index slides |
Python's own list works on the same idea. CPython grows it by a smaller factor than double, and other languages pick their own factor, but the trick is the same: grow by copying, so add at the end whenever you can.
Where you meet it
The list in your app grows this way. So does a long text built up a piece at a time, and data from the internet, where the program doesn't know how much is coming and keeps adding to the end. A sorted list like your contacts is the slow case: every new name goes in the right place and slides everyone after it, so huge sorted lists use other tricks.
Recap
- A dynamic array is a row of equal slots side by side, so any slot is one jump away.
- When it's full, it copies itself into a box twice the size. That's rare, so adding at the end stays cheap.
- Squeezing into the middle slides every item after it.
Try it yourself: in playlist_app.py, insert Jazz at index 0 instead of 1, and predict the shifts before you run it. When inserting at the front is your main job, a linked list does it without sliding anything.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
What a Data Structure Is, and How Memory Works
Memory is a long row of numbered boxes, and opening any box is equally quick. A data structure is an agreed way of arranging things in those boxes, plus a few small notes. See with six songs on a phone why every structure is quick at some things and slow at others.
Linked Lists: A Chain of Clues, Built in Python
In a linked list every node holds a value and the address of the next node. Build a treasure hunt chain in Python: a new first clue is two moves at any size, slipping a clue in or out is just changing next, but reaching clue number i is a walk of i hops.
Stacks: Last In, First Out, With the Undo Button
A stack is last in, first out: the newest thing you put on is the first thing you take off. Build Emma's undo button in Python from a list and one top index, push, pop and peek in one step each, undo after a million edits, and see what happens when you pop an empty stack.
Queues: First In, First Out, With a Ring of Cells
A queue is first in, first out: whoever joins the line first is served first. Build Kate's cinema ticket line in Python as a ring of four cells, where nobody steps forward and only head and tail move, serve a million people with the same four cells, then break it with a line that is already full.
