Python List insert() Method

Inserts an item into a list at specified position

Usage

Use insert() method to insert a single item at a specified index in a list. Note that other items are shifted to the right.

The method does not return anything; it modifies the list in place.

Syntax

list.insert(index,item)

Python list insert() method parameters
ParameterConditionDescription
indexRequiredIndex of an item before which to insert
itemRequiredAn item you want to insert

Examples

Example: Insert ‘yellow’ at 2nd position

L = ['red', 'green', 'blue']
L.insert(1,'yellow')
print(L)    # ['red', 'yellow', 'green', 'blue']

You can also use negative indexing with insert() method.

Example: Insert ‘yellow’ at 2nd position with Negative indexing

L = ['red', 'green', 'blue']
L.insert(-2,'yellow')
print(L)    # ['red', 'yellow', 'green', 'blue']

Index greater than list length

When you specify an index greater than list length, you do not get any exception. Instead, the item is inserted at the end of the list.

Example: Index greater than list length inserts item at the end

L = ['red', 'green', 'blue']
L.insert(10,'yellow')
print(L)    # ['red', 'green', 'blue', 'yellow']

insert() vs append()

Inserting item at the end of the list with insert() method is equivalent to append() method.

Example: Inserting item at the end with insert()

L = ['red', 'green', 'blue']
L.insert(len(L),'yellow')
print(L)    # ['red', 'green', 'blue', 'yellow']

is equivalent to

L.append('yellow')

insert() vs extend()

insert() method treats its argument as a single object.

Example:

L = ['red', 'green']
L.insert(2,'blue')
print(L)    # ['red', 'green', 'blue']

Use extend() method, if you want to add every item of an iterable to a list.

Example:

L = ['red', 'green']
L.extend('blue')
print(L)    # ['red', 'green', 'b', 'l', 'u', 'e']