1. Memory Architecture of CPython Lists
Dynamic Array with Over-Allocation
- Under the hood in CPython, a list is a PyListObject containing a pointer to a contiguous array of PyObject pointers.
- Indexing `lst[i]` is instantaneous O(1) arithmetic pointer offset.
- When appending beyond capacity, CPython reallocates the array with geometric growth (amortized O(1) append).
- Inserting or deleting at the beginning (`lst.insert(0, val)` or `lst.pop(0)`) requires shifting all subsequent pointers, costing O(N) time.
numbers = [10, 20, 30]
numbers.append(40) # O(1) amortized
first = numbers.pop(0) # O(N) linear time - shifts remaining items!
print("Remaining:", numbers)