list · Python
append / extend
Adds one element (append) or every element of an iterable (extend) at the end.
list.append(x, /); list.extend(iterable, /)
Complexity
| Best case | O(1) |
|---|---|
| Amortized | O(1) per element |
| Worst case | O(n) when the array must be reallocated |
| Extra space | O(1) amortized |
With spare capacity, one pointer is stored. Reallocation copies all pointers, but geometric over-allocation makes that rare enough to amortize to O(1).
Tested example
items = []
for value in (10, 20, 30):
items.append(value) # amortized O(1): CPython over-allocates spare slots
assert items == [10, 20, 30]
items.extend([40, 50]) # append many at once
assert len(items) == 5
Parameters
- x / iterable
- The element, or the elements to add.
Behaviour
- Returns
- None.
- Errors and preconditions
- MemoryError only.
- Changes
- The list grows by 1 (or by the iterable's length).
- Memory and invalidation
- Reallocation may move the pointer array (realloc).
See it step by step: the Dynamic arrays: capacity, resizing and amortized append lesson has an interactive 3D visualizer of the same mechanism.