Add item to a specific position in list Python Programming
Hello learners, in this Python tutorial we are going to learn how easily we can add item to a specific position in list in Python. In my previous tutorial, I have shown you How to add items to list in Python. Then I thought if someone needs to insert items to a specific position of a list in Python. Thus I came here again with a new tutorial to teach you how to add elements to a specific index position in a list.
Insert Item to specific position in a list in Python
You will glad to know that Python makes it easier for us with a predefined method insert()
This method has two parameters.
- Index – This is the position where the element is going to be inserted.
- Element – This is the element that you are going to insert.
I will provide some examples so that it can be more understandable.
Suppose, you have a list like this below:
my_list =[85,36,98,54]
Now you have to add an element to this list. But the element should be added to a particular position. You need to add the new element in between 36 and 98. That means the position of the new element has to be index no 2.
my_list =[85,36,98,54] my_list.insert(2,'this is inserted') print(my_list)
Output:
[85, 36, 'this is inserted', 98, 54]
You can use both integer or string values in the second parameter of insert() method.
Note: This method does not return any value.
Leave a Reply