Contents
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 – insert()
The syntax of insert() method is:
mylist.insert(index, item)
The items present from the specified index are shifted right and specified item is inserted at the index.
Example 1: Insert Item at Specified Index in 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)
Run Output
[21, 5, 8, 52, 36, 21, 87, 52]
Example 2: Insert Item at Start of 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)
Run Output
[36, 21, 5, 8, 52, 21, 87, 52]
Example 3: Insert Item at End of 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)
Run Output
[21, 5, 8, 52, 21, 87, 52, 36]
Example 4: Insert Item with Index out of Bounds of 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)
Run 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)
Run 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.
Related Tutorials
- Python Program to Find Largest Number in a List
- Python – Traverse List except Last Element
- How to Check if Python List is Empty?
- How to Get List of all Files in Directory and Sub-directories?
- Python – Count the items with a specific value in the List
- How to Sort Python List?
- How to Append List to Another List in Python? – list.extend(list)
- How to Access List Items in Python?
- Python Program to Find Smallest Number in List
- How to Get the list of all Python keywords?