Python List - Insert Item/Element at Specific Position
Python - Insert Item at Specific Index in List
To insert or add an item at specific position or index in a list, you can use insert() method of List class.
In this tutorial, we shall learn how to insert an item in a list, at given position, with the help of example Python programs.
Syntax of insert()
The syntax of insert() method in list class is
mylist.insert(index, item)
The items present from the specified index are shifted right and specified item is inserted at the index.
Examples
1. Insert given item at specified index in the list
In the following example, we have list of numbers. We will insert an item 36, in the list at index 4.
Python Program
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 36
index = 4
#insert item in mylist at index
mylist.insert(index, item)
print(mylist)
Output
[21, 5, 8, 52, 36, 21, 87, 52]
2. Insert given item at beginning of the list
In the following example, we will insert 36, at the start of the list. To insert at start, we need to provide the index as 0 to insert() method.
Python Program
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 36
index = 0 #1st position
#insert item in mylist at index
mylist.insert(index, item)
print(mylist)
Output
[36, 21, 5, 8, 52, 21, 87, 52]
3. Insert given item at the end of the list
We will insert an item at end of the list. To insert item at the end, provide index, as length of the list, to insert() method.
Python Program
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 36
index = len(mylist)
#insert item in mylist at index
mylist.insert(index, item)
print(mylist)
Output
[21, 5, 8, 52, 21, 87, 52, 36]
4. Insert item with index that is out of bounds for given list
If the index provided to insert() method is more than the length of the list, it just appends the item to the list.
Here in this example, the index provided is way out of bounds and more than the length of the list.
Python Program
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 36
index = 1000 #index out of bounds of list
#insert item in mylist at index
mylist.insert(index, item)
print(mylist)
Output
[21, 5, 8, 52, 21, 87, 52, 36]
If you provide a negative index, the item is inserted at the beginning of the list.
Python Program
mylist = [21, 5, 8, 52, 21, 87, 52]
item = 36
index = -10 #index out of bounds of list
#insert item in mylist at index
mylist.insert(index, item)
print(mylist)
Output
[36, 21, 5, 8, 52, 21, 87, 52]
Summary
In this tutorial of Python Examples, we learned how to insert an item at given position in the list.