RightSignal
1 of 4

Your RightSignal

Concept of the day1 / 3

Dynamic arrays

The concept

Why adding to a Python list almost never slows down

An array stores items side by side in one fixed block of memory. When the block is full, you cannot simply extend it, because the next bytes may already be in use. A dynamic array solves this by moving everything into a new, larger block.

The trick is to multiply the capacity (the number of slots) at each move, for example by doubling it. Moves then become so rare that an append costs a constant amount on average, which is called amortised cost.

What it’s forCounts the total copying work when you append n items to an array that doubles whenever it fills up.

copies = 1 + 2 + 4 + … + n/2 = n − 1

n
number of items appended, here a power of 2 such as 16
1, 2, 4 …
items copied at each resize, one resize per doubling

What it givesFewer than n copies in total, so each append costs O(1) on average.

  1. Append 16 items starting from capacity 1
  2. Resizes copy 1 + 2 + 4 + 8 = 15 items
  3. 15 copies + 16 writes = 31 steps, under 2 per append