Python List insert()

The insert() method inserts an item at a specific position within a list.

Syntax

list.insert(index, element)

Parameters

index : (Required) The position where you want to insert the item. The index starts at position 0. If the index is greater than the length of the list, the element is added to the end of the list.

element: (Required) The value you want to insert into the list.

Return Value

The insert() method doesn’t return any value i.e. return None. It modifies the original list.

Example 1: Insert item at the beginning of the list

my_list = [5, 10, 15, 20]

my_list.insert(0, 99)
print(my_list) # [99, 5, 10, 15, 20]

The indexes in Python start at the position 0. This means the first element is at index 0, the second element is at the index 1 , and so on. To insert the item at the beginning of the list, you need to pass 0 as the index value.

When you insert an element, all subsequent elements in the list are shifted one position to the right to make space for the new element.

Example 2: Insert item at a specific index

my_list = ["apple", "banana", "mango"]

# Inserting item at index 1
my_list.insert(1, "orange")
print(my_list) # ['apple', 'orange', 'banana', 'mango']

Example 3: Insert item at the end of the list

my_list = ["apple", "banana", "mango"]

# Inserting item at end of the list
my_list.insert(len(my_list), "orange")
print(my_list) # ['apple', 'banana', 'mango', 'orange']

The len() function returns the length of the list.

You should use the append() method to add an element to the end of the list because it is more efficient than the insert() method.