Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 1

How a Python List Grows

Inspect the pointer-array layout behind CPython lists, observe over-allocation steps with sys.getsizeof, and see why O(1) indexing and O(n) front shifts follow directly from contiguous storage.

Contentsand lesson path

What you will learn

  • State the cost of common list and string operations (index, append, insert at front, slice, concatenate, membership test) and pick the cheaper alternative.

Prerequisites: Complexity Analysis

01. Why it matters

In Worst Case, Average Case and Amortized Cost, you saw why a dynamic array keeps append at O(1) amortised time. Yet beginners often hit two surprises when moving from theory to Python list objects: appending a few giant objects does not make sys.getsizeof(lst) explode, while calling lst.insert(0, x) inside a loop slows sharply as the list grows: on our lab machine (CPython 3.12.13), 50,000 front inserts took about 0.35 s, against under 2 ms for 50,000 appends followed by one reverse().

Both behaviours come from one physical design choice inside CPython: a list is not a linked chain of nodes, and it does not store object payloads inline side by side. It is a contiguous array of pointers (references) with spare capacity reserved at the tail. Understanding that layout lets you predict both memory growth and operation cost without memorising arbitrary rules.

02. Contiguous pointer array vs inline values

Imagine building a Python list that holds [42, "refund", [1, 2]]. Every element can have a different type and byte size. If Python packed the actual object bytes back-to-back inside one array, computing the address of lst[k] would require scanning earlier items because each item could be a different width. Instead, CPython stores a flat array of fixed-width object references (8 bytes per pointer on a 64-bit machine), while the objects themselves live elsewhere on the heap.

Look at the mechanism this unlocks and what it forces:

  • Instant indexing (lst[k]): because every slot is the same 8-byte width, Python finds slot k in O(1) arithmetic (base_address + k * 8), regardless of list length or element size.
  • Expensive front shifts (lst.insert(0, x) or lst.pop(0)): keeping all references contiguous means inserting at index 0 must slide every existing pointer one slot right (n pointer moves), and popping index 0 must slide n - 1 pointers left. That is O(n) work, not O(1).
  • Simplification boundary: measuring sys.getsizeof(lst) reports only the list header plus its pointer table, not the memory of the strings, dicts, or nested lists those pointers reference. On a 32-bit build each slot is 4 bytes instead of 8, and other Python implementations such as PyPy may lay out homogeneous integer lists differently.
Text · CPython list head + over-allocated pointer buffer (64-bit simplified)
PyListObject head                 Pointer buffer (8 bytes per slot)
+---------------------+          +-------+-------+-------+-------+-------+
| size = 3            | -------> | ptr 0 | ptr 1 | ptr 2 | spare | spare |
| allocated = 5       |          +-------+-------+-------+-------+-------+
+---------------------+              |       |       |
                                     v       v       v
                                    42   "refund"  [1, 2]

03. Observing over-allocation in CPython

When size reaches allocated, append() allocates a larger pointer array and copies only the 8-byte pointers—not the objects they point to. Let us watch CPython grow an empty list from 0 to 34 elements using sys.getsizeof. Notice that bytes jumps in steps (56 -> 88 -> 120 -> 184 -> ...), showing spare pointer slots reserved ahead of time.

Python · watching list capacity jumps and in-place vs sliced reversal
import sys

lst: list[int] = []
prev_size = sys.getsizeof(lst)
print(f"len=0  bytes={prev_size}")
for i in range(1, 35):
    lst.append(i)
    cur_size = sys.getsizeof(lst)
    if cur_size != prev_size:
        slots = (cur_size - sys.getsizeof([])) // 8
        print(f"len={i:<2} bytes={cur_size} (approx slots={slots})")
        prev_size = cur_size

nums = [10, 20, 30, 40]
nums.reverse()
print("after reverse():", nums)
rev_copy = nums[::-1]
print("slice [::-1] is new object:", rev_copy is not nums, rev_copy)
Expected output (64-bit CPython 3.12)
len=0  bytes=56
len=1  bytes=88 (approx slots=4)
len=5  bytes=120 (approx slots=8)
len=9  bytes=184 (approx slots=16)
len=17 bytes=248 (approx slots=24)
len=25 bytes=312 (approx slots=32)
len=33 bytes=376 (approx slots=40)
after reverse(): [40, 30, 20, 10]
slice [::-1] is new object: True [10, 20, 30, 40]

Look at the output: after an empty list (56 bytes), the first append reserves 4 slots (88 bytes), then 8, 16, 24, 32, 40. Notice the empty list already weighs 56 bytes for the PyListObject header (storing length, allocated slot count, and pointer to the buffer). As the list grows, CPython jumps by larger steps so that resizes happen exponentially less often. At larger lengths CPython increases capacity by a modest fraction (roughly an eighth of the length plus a small constant) so memory overhead stays modest while append() remains O(1) amortised. What if you stored 10-megabyte strings inside lst instead of small integers? The pointer table sizes above (56, 88, 120, ...) would stay identical, because lst only holds 8-byte references to objects stored elsewhere on the heap.

What happens when you remove items with pop()? CPython does not shrink the pointer buffer on every single removal—otherwise alternating append and pop around a capacity boundary would copy the array on every step. Instead, the buffer shrinks only once the size drops below half of the allocated slots, and even then CPython keeps about an eighth of spare room (lst.clear() releases the buffer completely). Similarly, inserting at index 0 with lst.insert(0, x) must shift pointer n - 1 into slot n, then n - 2 into n - 1, all the way down to slot 0 before writing x, which costs O(n) pointer moves every call.

Notice also the last two lines: nums.reverse() flips pointers in place inside the existing buffer (O(1) extra space), whereas nums[::-1] allocates a brand-new list and copies n pointers (O(n) extra space). Keep that distinction in mind whenever you iterate backwards: reversed(nums) returns an O(1)-space iterator, nums.reverse() mutates the original list, and nums[::-1] copies every pointer into a fresh list. Similarly, nums.copy() or nums[:] makes a shallow copy—it copies the n 8-byte pointers in O(n) time, so nested mutable lists inside nums remain shared between both outer lists until explicitly copied as well.

When not to use a Python list: avoid relying on a contiguous list in three common workloads where its pointer-array layout fights against your access pattern:

  • Frequent additions or removals at index 0: building a queue or reversing by repeated insert(0, x) turns n operations into O(n^2) pointer shifts. Use collections.deque (see Stacks, Queues & Deques) or append at the tail and call reverse() once.
  • Frequent membership checks (x in items): scanning a list takes O(n) because elements sit in insertion order, not by key. Switch to a set or dict when order or duplicates are unneeded or lookups dominate (Hashing & Hash Tables).
  • Tightly packed numeric buffers or zero-copy slices: every integer in a Python list is a separate heap object plus an 8-byte pointer. If you need raw contiguous bytes or zero-copy views across millions of numbers, bytearray with memoryview (or specialised numerical arrays) avoids per-element Python object headers.

04. Check your understanding

Practice check · 2 questions

Pointer arrays and list growth

Predict how CPython lists behave under growth, indexing and deletion.

Q1. Lists `a` and `b` are each built by the same 1,000 `append` calls: `a` receives the small integers `0..999`, and `b` receives 1,000 strings that are each `10 KB` long. How do `sys.getsizeof(a)` and `sys.getsizeof(b)` compare?
Q2. You delete index `0` from a list of `n` items with `del items[0]` vs deleting the middle index `del items[n // 2]`. How do their time complexities compare?
Practice only: not graded, not saved, not evidence.

05. Apply it

Run your own sys.getsizeof probe in Python from len = 0 up to len = 200 and record every jump in byte size. Then call lst.pop() repeatedly down to len = 0 while printing sys.getsizeof(lst)—observe whether CPython shrinks the pointer buffer only after many pops or stays flat until below half capacity. Finally, create nested = [[1, 2], [3, 4]], take shallow = nested.copy(), mutate shallow[0].append(99), and confirm why nested[0] also changed even though nested is shallow is False.

Next, collect all common list and str operation costs in A Cost Table for Lists and Strings.

06. Review prompt

Without looking back:

  1. Why does CPython list store pointers instead of inline values, and what two operation costs follow from that choice?
  2. What does sys.getsizeof(my_list) include, and what does it leave out?
  3. Compare nums.reverse() and nums[::-1] in both time and auxiliary space.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check