Add item to a specific position in list Python Programming
In this tutorial, we are going to learn how to add an item to a specific position in a list in Python.
We can do this by using the below methods:
- list.insert()
- List slicing
In my previous tutorial, I have shown you How to add items to a Python list.
Insert Item to a specific position using list.insert()
You will be glad to know that Python makes it easier for us with a predefined method which is the insert()
method.
Below is given the syntax for the insert()
list.insert(Index, Element_to_be_inserted)
This method has two parameters.
- Index – This is the position where the new element is going to be inserted.
- Element – This is the new element that you are going to insert into the existing list.
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 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.
List slicing to insert item or items to a specific index of a list
We can use list slicing also to do the same.
This might be a little bit complicated if you are not good at list slicing. Though, I will make it simple so that you can understand it.
my_list = [85, 36, 98, 54] items_to_insert = ['codespeedy', 'python', 'java'] my_list[1:1] = items_to_insert print(my_list)
Output:
[85, 'codespeedy', 'python', 'java', 36, 98, 54]
So what does my_list[1:1]
mean?
It’s nothing but the start index
and end index
where you want to put the new items.
If you want to insert to an exact position then keep both the start and end index the same. Otherwise, it will replace elements.
If you want to insert a single element in it then it will not cause an issue. Let’s have a look at this example:
my_list = [85, 36, 98, 54] items_to_insert = ['codespeedy'] my_list[3:3] = items_to_insert print(my_list)
Output:
[85, 36, 98, 'codespeedy', 54]
Leave a Reply