List Methods
insert()
Insert an item at a specified index.
list.insert(index, item)
list.insert() inserts item at the given index, shifting all subsequent elements one position to the right.
Inserting at index 0 prepends the item to the beginning of the list.
Parameters
| Name | Description |
|---|---|
| index | The position where the new element should be inserted. |
| item | The item to insert. |
Returns
None — the list is modified in place.
Try it
Run it and change it
numbers = [1, 2, 4, 5] numbers.insert(2, 3) print(numbers)
Worth knowing
- Out of bounds indices: An index larger than the list length appends the item to the end; a negative index smaller than
-len(list)prepends it to the front without error. - Performance consideration: Inserting at the front (index 0) requires shifting all elements and is
O(n). For frequent insertions at both ends, usecollections.deque.