Arrays and Python Lists

An array organizes elements by contiguous index; CPython's list uses a dynamically resized array of object pointers, offering O(1) indexed access and amortized O(1) tail appends while requiring O(n) element shifts for head insertions.

One-Line Definition

An array organizes elements by numerical index in contiguous memory; CPython's built-in list is a dynamically resized array of object pointers, giving O(1)O(1) indexed lookup and amortized O(1)O(1) tail appends while requiring O(n)O(n) element shifts for insertions or removals near the head.

Why It Matters

  • Contiguous arrays are the underlying building block for stacks, binary heaps, and hash-table bucket arrays.
  • Understanding contiguous memory layout immediately explains why appending to the end of a list is fast while inserting at index 0 is slow—and why unboxed NumPy arrays outperform lists of boxed Python objects (see k1.lib.numpy).

Operating Boundaries

A CPython list stores a contiguous array of 8-byte object references (pointers), not the heap-allocated Python objects themselves. Accordingly, sys.getsizeof(lst) measures only the list header and pointer buffer without recursively summing the referenced elements; likewise, multi-dimensional tensors may be non-contiguous strided views rather than flat contiguous buffers.

How It Works / Diagram

CPython's list is backed by a C pointer array that **over-allocates** capacity proportionally whenever it grows, ensuring that a sequence of append() calls runs in amortized constant time. See the CPython source (https://github.com/python/cpython/blob/main/Objects/listobject.c) and the official Python Wiki time-complexity table (https://wiki.python.org/moin/TimeComplexity).

Figure 1

Direct memory address arithmetic (the reason random access by index ii is O(1)O(1)):

addr(i)=base+i×slot_size \text{addr}(i) = \text{base} + i \times \text{slot\_size}
Operation Time Complexity Mechanical Reason
a[i] read / write O(1)O(1) Direct pointer offset calculation
append(x) / tail pop() Amortized O(1)O(1) Writes into spare pre-allocated slot; resizes only occasionally
insert(0, x) / pop(0) O(n)O(n) Every subsequent pointer slot must shift by one position
x in a O(n)O(n) Linear scan comparing elements sequentially

Runnable Example

Observing capacity step-ups during appends, timing tail vs. head operations, comparing memory footprint against Python's unboxed array.array, and demonstrating the classic 2D list aliasing pitfall (recorded on Python 3.15.0):

# File: examples/08_array.py
# Arrays: contiguous memory + O(1) indexed access; Python's list is a dynamic pointer array
import sys, time, array
from timeit import timeit

lst = []
sizes = []
for i in range(20):
    lst.append(i)
    sizes.append(sys.getsizeof(lst))
print("List byte size steps during append (over-allocation):", sorted(set(sizes)))

big = list(range(1_000_000))
t_idx = timeit(lambda: big[500_000], number=100_000)
t_end = timeit(lambda: big.append(0) or big.pop(), number=100_000)
t_head = timeit(lambda: big.insert(0, 0) or big.pop(0), number=1_000)
print(f"Random access {t_idx/100_000*1e9:.0f} ns | Tail push/pop {t_end/100_000*1e9:.0f} ns | Head insert/pop {t_head/1_000*1e6:.0f} µs")

# Unboxed typed array: array.array stores raw C values without per-element Python object headers
a = array.array("d", range(1000))
print("list of 1000 floats ~", sys.getsizeof(list(map(float, range(1000)))) + 1000 * sys.getsizeof(1.0), "bytes",
      "| array('d') ~", sys.getsizeof(a), "bytes")

# Classic 2D grid trap: [[0]*3]*3 duplicates references to the exact same inner row list
bad = [[0] * 3] * 3; bad[0][0] = 1
good = [[0] * 3 for _ in range(3)]; good[0][0] = 1
print("bad :", bad); print("good:", good)

Recorded output:

List byte size steps during append (over-allocation): [88, 120, 184, 248]
Random access 20 ns | Tail push/pop 42 ns | Head insert/pop 546 µs
list of 1000 floats ~ 32856 bytes | array('d') ~ 8320 bytes
bad : [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
good: [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
  • sys.getsizeof(lst) climbs in discrete steps (88 → 120 → 184 → 248 bytes), proving that append does not reallocate on every call.
  • Comparing the nanosecond tail operation against the microsecond head operation on a 1-million-element list illustrates the real-world gap between O(1)O(1) and O(n)O(n).
  • Because a Python list stores 8-byte pointers to 24-byte heap float objects, whereas array('d') packs raw 8-byte IEEE-754 doubles contiguously, the unboxed array uses roughly one-fourth the memory.

Common Pitfalls

  • Initializing a 2D grid with [[0]*3]*3: Outer repetition copies three references to the exact same inner list object, so mutating one row mutates all three rows simultaneously (see k1.py.object-reference). Always use a list comprehension: [[0]*3 for _ in range(3)].
  • Using list.pop(0) as a FIFO queue: Shifting n−1n-1 elements on every dequeue turns an O(n)O(n) loop into O(n2)O(n^2); use collections.deque instead (see k2.ds.queue).
  • Assuming a Python list stores unboxed values: It stores object references, which is why a single list can hold heterogeneous types at the cost of pointer indirection.
  • Running heavy numerical loops over Python lists: Use vectorized NumPy arrays instead.

Relevance to AI Engineering

  • Tensors are multi-dimensional arrays parameterized by shape and strides: In PyTorch and NumPy, a tensor's shape and stride metadata map multi-dimensional indices onto a 1D memory buffer—the exact mechanism behind view(), reshape(), and contiguous().
  • Pre-allocating batch buffers: When sequence lengths or batch sizes are known ahead of time, pre-allocating a fixed tensor or array buffer avoids repeated resize allocations and memory fragmentation.
  • Token ID sequences and embedding lookup tables are fundamentally contiguous arrays indexed in O(1)O(1) time.

Further Reading

Concept Check

If list.append() has an amortized time complexity of O(1)O(1), why can a single individual append() call still occasionally take a long time?

Reference answer: Because when the underlying pointer buffer reaches full capacity, that specific append() must allocate a larger buffer and copy all nn existing pointers over (O(n)O(n) worst-case for that single call); amortized O(1)O(1) describes the average cost per operation spread across a long sequence of appends.

Verification & Reproduction

Verified on: 2026-10-14. Example status: Passed. Execution log: 08_array.py.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram