Lesson · Python Internals
List Internals
95 min readList Internals
CPython lists are dynamic arrays of object references. Overallocation makes repeated append efficient on average, while insertion, deletion, and slicing can require moving or copying references.
Learning goals
- Explain why a list is a contiguous array of references while the referenced objects live elsewhere.
- Read
sys.getsizeofbesidelento see capacity exceed logical length. - Describe overallocation as the trade that amortizes append, and identify which individual append pays the copy.
- Predict the cost of
insert(0, x),pop(0), anditems[:]from the array layout. - Decide when a list's costs make
collections.dequethe better structure for a workload.
Mental model
The two quantities in the diagram are what make list behavior understandable: len(items) counts logical elements, while getsizeof reveals the allocated slots, and append either consumes a spare slot cheaply or grows the array and copies every existing reference. Overallocation, amortized append, and the price of insert and delete all follow from that one picture.
Length is logical, allocation is real
growth copies, spare slots are free
Mental model
the same mechanism as a compact list
logical length ≤ allocated capacity append → use spare slot OR grow/copy references
Core idea
A CPython list is a dynamic array of references with a logical length and a larger allocated capacity. Appends usually write into spare capacity and occasionally trigger a grow-and-copy, which averages out to constant time per append; operations at the front or middle shift references, and slices copy them. The layout is an implementation detail, but the costs it creates are visible in the language's time behavior.
Dynamic array model
A CPython list stores a contiguous dynamic array of references to Python objects. The referenced objects themselves can live elsewhere in memory.
Capacity
List capacity is the number of reference slots currently allocated, which can exceed logical length. Spare capacity reduces the frequency of reallocation during append-heavy growth.
Overallocation
CPython lists often allocate spare capacity beyond the current logical length so several appends can occur without reallocating. The exact growth formula is an implementation detail and can change.
Append amortization
Most appends use existing spare capacity, while occasional appends allocate a larger array and copy references. Averaged across many appends, this yields amortized constant-time behavior.
Insert/delete costs
Inserting or deleting an element in the middle or at the front shifts every reference after it by one slot, which makes those operations linear in the list's length; append and pop() at the end avoid shifting and are the cheap positions. This is a consequence of the contiguous array: keeping slots adjacent is what makes indexing constant time, and the same property forces the shift when elements move.
Slice copying
A normal list slice constructs a new list containing references to the selected objects. It is a shallow structural copy, not a deep copy of the elements.
Walkthrough
items = []creates a list with zero elements but a small non-empty allocation, so the firstsys.getsizeof(items)already reports bytes for the object and its initial slot array.- The loop appends integers and prints only when
getsizeofchanges, so each printed line marks a growth step where the array gained slots and the printedlengthis the element count at that moment. - The gaps between prints are not equal, because CPython overallocates by a factor: early appends grow the table often, and later appends reuse a larger margin, which is the amortization argument visible in the data.
- Predict before running: the first few printed lengths where growth happens, and whether
getsizeofever decreases during the loop.
Experiments to try
- Run 1,000,000 appends and collect every distinct (length, size) pair; tabulate them and identify the growth ratios between consecutive enlargements.
- Pop elements with
items.pop()from a long list and watchgetsizeof; observe whether the list ever gives capacity back rather than assuming either answer. - Time
items.insert(0, x)againstitems.append(x)over 10,000 operations and explain the gap with the number of shifted references. - Take a slice
items[:]and append to the copy; confirm the original is unchanged and explain that the slice copied references, not the int objects.
Playable lesson
Lab: List capacity growth
Graph logical length and allocated size as append operations occur. Emphasize amortized behavior instead of a fixed implementation formula.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
List capacity growth
Slots
allocated 0 · spare 0
The difference is spare capacity: appends into it cost nothing beyond the write.
Allocation as appends happened
bar height is allocated slots, marks are growth
Each bar is a checkpoint: the block allocated after that many appends. Taller, amber bars are the growth events, where the block was replaced and every reference copied.
Appends done
0
References copied
0
0.0 per append on average
Spare slots
0
free slots before the next growth
Predict first
How much room does an empty list have for elements?
A list begins with no elements and no allocation. The two numbers to watch are `len(items)`, the logical length, and `sys.getsizeof(items)`, which reveals the allocated slots.
Common mistakes
- Treating
appendas fixed cost per call: it is amortized constant, and the occasional append that triggers a grow copies every reference, so one call can cost far more than the rest. - Inserting or removing at the front in a loop: each
insert(0, ...)orpop(0)shifts every reference after the position, which turns the loop quadratic. - Reading
len(items)as the allocated slots: capacity is usually larger than the length, andgetsizeofis what exposes the gap. - Believing a slice copies the elements:
items[:]copies the array of references, so the new list is independent while the element objects remain shared, and mutating a contained mutable object through one list is visible through the other.
Practice: Easy
- Run the worked example and write the (length, size) pairs into a table; mark each row where the size jumped and compute the ratio to the previous size.
- Extend the loop to 1,000 elements and list the lengths where growth happens; state the smallest gap between two growth points.
- Build the same 100 elements with five
extend(range(20))calls and with 100appendcalls, printing every size change; compare the number of growth events.
Practice: Medium
- Write a function that reports
(len(items), getsizeof(items))before and afteritems.pop()on a 100-element list; pop down to ten elements and describe when capacity shrinks. - Time
insert(0, x)versusappend(x)for 10,000 elements and explain the ratio with the number of shifted references per operation. - Take
left = original[:], append"x"toleft, and show the original is unchanged; then put a shared nested list inside both and show that mutations to the nested list appear in both, and name which copy the slice performed.
Practice: Hard
- Build a growth report tool: append in a loop, record (length, size) whenever the size changes, and compute from the output the growth factor between the last few enlargements and the average bytes per element at the end.
- Create a queue comparison lab: run the same workload with a list using
pop(0)and withcollections.dequeusingpopleft()for 100,000 items, and explain the difference with shifting versus the deque's block layout. - Recreate the worked example in reverse: start from a 1,000-element list, shrink it with
pop()in a loop, record every size change, and describe the shrink policy you observe; compare it with the growth policy.
Lesson checklist
- I can explain the difference between
len(items)and the allocated capacity. - I can identify growth events from
getsizeofand describe what happens during one. - I can argue why append is amortized constant time and which call pays the copy.
- I can predict the cost of inserting, deleting, and slicing, and name a case where
dequeis the better tool.
Remember
CPython lists are dynamic arrays of references: `len` tracks logical elements, capacity tracks allocated slots, and `append` either uses a spare slot or grows the array and copies every reference, which averages out to constant time per append. The same contiguous layout makes indexing fast and makes front or middle inserts and deletes pay a shift, while slices copy the array of references rather than the objects. Keep capacity and amortization in mind when you interpret `getsizeof` or choose a container for queue-like work.
Interview angles
What is the main purpose of **Dynamic array model**?+
A CPython list stores a contiguous dynamic array of references to Python objects. The referenced objects themselves can live elsewhere in memory.
What should you pay attention to when using **Capacity**?+
List capacity is the number of reference slots currently allocated, which can exceed logical length. Spare capacity reduces the frequency of reallocation during append-heavy growth.
How does **Overallocation** fit into this lesson?+
CPython lists often allocate spare capacity beyond the current logical length so several appends can occur without reallocating. The exact growth formula is an implementation detail and can change.
Why is `pop(0)` a poor fit for a queue while `append` plus `pop()` works well for a stack?+
pop(0) removes the first element and shifts every remaining reference one slot left, so a queue built that way costs linear work per removal. append and pop() operate at the end, where no shift is needed, which makes a list a natural stack; for queue behavior, collections.deque.popleft() avoids the shift.