add
list.insert
Inserts item x before index i, shifting subsequent elements right. Mutates in place, returns None; O(n) because it shifts trailing elements.
list.insert(i, x) Parameters
| Parameter | Purpose |
|---|---|
| i | Target index; 0 inserts at head, len(lst) appends. Negative indices count from the end. |
| x | The element to insert (single object, not unpacked). |
Examples
>>> lst = [1, 2, 4]
>>> lst.insert(2, 3)
>>> lst
[1, 2, 3, 4] Insert 3 before index 2.
>>> lst = [1, 2, 3]
>>> lst.insert(0, 'start')
>>> lst
['start', 1, 2, 3] insert(0, x) prepends — but is O(n); use collections.deque.appendleft for hot paths.
>>> lst = [1, 2, 3]
>>> lst.insert(99, 'end')
>>> lst
[1, 2, 3, 'end'] Out-of-range index clamps to the end — no IndexError.
>>> lst = [1, 2, 3]
>>> lst.insert(-1, 'x')
>>> lst
[1, 2, 'x', 3] Negative index inserts before that position, not after.
Gotcha
insert is O(n) — avoid inserting near the head in tight loops. Out-of-range indices silently clamp instead of raising; do not rely on IndexError.
Related methods
list.append
Appends a single item x to the end of the list, mutating it in place. Always returns None — it does not return the modified list.
list.extend
Extends the list by appending every element from an iterable, in order. Mutates in place and returns None; equivalent to `list += iterable`.
list[i] / list[i:j:k]
Subscript syntax to read a single element (by index) or a new list (by slice). Slicing always returns a new shallow copy; out-of-range slice bounds are silently clamped while single-index access raises IndexError.
← All Python list methods · Dict methods · list vs tuple vs set