How does Python's list implementation achieve amortized O(1) append performance despite lists being dynamically resizable arrays under the hood?
Short answer
CPython's list over-allocates extra capacity beyond the current size whenever it needs to grow, so most append() calls just write into already-allocated space (O(1)); only occasionally, when capacity is exhausted, does it need to allocate a larger buffer and copy all elements…
Advertisement
AModel answer
CPython's list over-allocates extra capacity beyond the current size whenever it needs to grow, so most append() calls just write into already-allocated space (O(1)); only occasionally, when capacity is exhausted, does it need to allocate a larger buffer and copy all elements (O(n)) — averaged ('amortized') across many appends, this works out to O(1) per append.
import sys
lst = []
for i in range(10):
lst.append(i)
print(len(lst), sys.getsizeof(lst)) # size (in bytes) jumps in chunks, not every single appendReal-world example
Understanding why appending to a Python list in a loop is generally efficient, despite lists being resizable arrays rather than linked lists.
Likely follow-ups
- How does this over-allocation strategy differ from what happens when you use list.insert(0, x) repeatedly instead of append()?
Related topics