list · Python
insert
Inserts before position i, shifting later elements right. Out-of-range i is clamped, never an error.
list.insert(i, x, /)
Complexity
| Best case | O(1) at the end |
|---|---|
| Worst case | O(n) at the front |
| Extra space | O(1) amortized |
All elements from i on move one slot (memmove of len − i pointers).
Tested example
items = ["a", "c", "d"]
items.insert(1, "b") # shifts "c" and "d" right
assert items == ["a", "b", "c", "d"]
items.insert(100, "e") # an index past the end appends: no error
items.insert(-1, "x") # negative index counts from the end
assert items == ["a", "b", "c", "d", "x", "e"]
Parameters
- i
- Position; negative counts from the end; values past either end are clamped.
- x
- The element.
Behaviour
- Returns
- None.
- Errors and preconditions
- None for any integer i.
- Changes
- The list grows by 1.
- Memory and invalidation
- May reallocate like append.
See it step by step: the Dynamic arrays: capacity, resizing and amortized append lesson has an interactive 3D visualizer of the same mechanism.