
In this post, you will learn how to insert an element into a list in a specific location.
Insert in Python –
To insert an element in any position in a list we use the insert method.
Syntax of Insert –
list.insert(index, element)
Index – this is the index of the element before which you want to insert the element
element – The element that you want to insert.
In [4]: fruits = ['Banana','Apple','Orange']
Here we have a fruit list. Now let’s say that you want to insert Mango at the beginning of the list. To do so you have to write
In [5]: fruits.insert(0, 'Mango')
In [6]: fruits
Out[6]: ['Mango', 'Banana', 'Apple', 'Orange']
And if you want to insert Grapes ahead of Apple.
In [7]: fruits.insert(2, 'Grapes')
In [8]: fruits
Out[8]: ['Mango', 'Banana', 'Grapes', 'Apple', 'Orange']