Python List insert Function

This Python function is useful for inserting a new item into the existing list at the user-specified index. In this section, we discuss how to use this Python List insert function with practical examples, and the syntax of this function is:

 list.insert(New_item, index_position)

Python insert List Function Example

This method helps us to add a given item (New_item) or element at the given index position. The below code adds 50 at index position 2.

TIP: Please refer to the List and functions articles to understand everything about them in Python.

a = [15, 20, 35, 90]

print("Original Items are : ", a)
a.insert(2, 50)
print("Items are          : ", a)
Original Items are :  [15, 20, 35, 90]
Items are          :  [15, 20, 50, 35, 90]

In this program, we are placing three values into an integer.

a = [10, 20, 30, 40]

print("Original Items are : ", a)
a.insert(1, 70)
a.insert(3, 50)
a.insert(0, 120)
print("Items are          : ", a)
Original Items are :  [10, 20, 30, 40]
Items are          :  [120, 10, 70, 20, 50, 30, 40]

In this example, we declared a string of words. Next, we used this python list insert function to put the element at a given index position 1.

Fruits = ['Apple', 'Orange', 'Kiwi', 'Grape']

print("Original Elements are : ", Fruits)
Fruits.insert(1, 'Banana')
print("Elements are          : ", Fruits)
Original Elements are :  ['Apple', 'Orange', 'Kiwi', 'Grape']
Elements are          :  ['Apple', 'Banana', 'Orange', 'Kiwi', 'Grape']

This program is the same as the first example. However, this time, we are allowing the user to enter the length. Next, we used the For Loop to append those number of elements.

intLi = []
 
number = int(input("Please enter the Total Number of Elements: "))
for i in range(1, number + 1):
    value = int(input("Please enter the Value of %d Element : " %i))
    intLi.append(value)
    
print("Original Items are : ", intLi)

item = int(input("Please enter the New Item : " ))
position = int(input("Please enter the New Item : " ))
intLi.insert(position, item)
print("Final Items are          : ", intLi)
Python Insert List Items function

This time, we used this on the Nested list to add item at a given position 2 (index).

MixLi = [[71, 222], [222, 13], [14, 15], [99, 77]]
    
print("Original Items are : ", MixLi)
MixLi.insert(2, [33, 55])
print("Items are          : ", MixLi)
Original Items are :  [[71, 222], [222, 13], [14, 15], [99, 77]]
Items are          :  [[71, 222], [222, 13], [33, 55], [14, 15], [99, 77]]

Let me use this one on the Mixed List.

MiLi = ['apple',  1, 5, 'Kiwi', 'Mango']
    
print("Original Items are : ", MiLi)
MiLi.insert(2, 'Banana')
print("Items are          : ", MiLi)
Original Items are :  ['apple', 1, 5, 'Kiwi', 'Mango']
Items are          :  ['apple', 1, 'Banana', 5, 'Kiwi', 'Mango']