Python Function Reference

list.insert

Insert an item into the list before the given index.

Python 3.13
list.insert(i, x)

Parameters

iint
The index before which the item goes; if it exceeds the length of the list, the item is added to the end.
xAny
The item to insert.

Return value

Nothing (None); the list is changed in place.

Examples

Inserting an item at an index

Python 3.13
a = [1, 3]
a.insert(1, 2)
print(a)
[1, 2, 3]

Inserting at the beginning

Python 3.13
a = [1, 2]
a.insert(0, 0)
print(a)
[0, 1, 2]

Details

A negative index counts from the end: a.insert(-1, x) puts the item before the last one. Inserting at the beginning shifts all items, so it is slow for a long list; for frequent inserts at the front, use collections.deque.

See also

Where to learn