In this article we will discuss how to insert an element in list at specific position.

Inserting an element in list at specific index using list.insert()

In python list provides a member function insert() i.e.

It accepts a position and an element and inserts the element at given position in the list.

Let’s see an example,

Suppose we have a list of strings i.e.

Now let insert ‘why’ at 3rd position in the list i.e.

Index will start from 0 in list. So, element will be inserted at 3rd position i.e. after 0,1 & 2.

So, list contents will be now,

Inserts an element at beginning of list

To insert the element at the front of above list, call insert() function i.e.

So, list contents will be now,

Insert all elements of another list at specific index in given list

Suppose we have two lists i.e.

Now Insert all the elements of list2 at 3rd position in list1

Method 1:

Iterate over list2 in reverse and keep on inserting element at 3rd index in list1 using list.insert() i.e.

 

Method 2:

Splice list1 from 0 to 2 and merge all elements of list2 in it. Then merge all the remaining elements of list from 3 to end i.e.

In both cases lists content will be now,

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.