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 –
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 : 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 : fruits.insert(0, 'Mango') In : fruits Out: ['Mango', 'Banana', 'Apple', 'Orange']
And if you want to insert Grapes ahead of Apple.
In : fruits.insert(2, 'Grapes') In : fruits Out: ['Mango', 'Banana', 'Grapes', 'Apple', 'Orange']