Home »
Python
Python List | insert() Method with Example
Python List insert() Method with Example: In this article, we are going to learn about list.insert() Method with Example.
Submitted by IncludeHelp, on August 14, 2018
list.insert() Method
insert() is an inbuilt method in python, which is used to add an element /item at specified index to the list.
insert() is able to add the element where we want i.e. position in the list, which we was not able to do the same in list.append() Method.
Syntax:
list.insert(index, element)
Here,
- list is the name of the list.
- index is the valid value of the position/index.
- element is an item/element to be inserted.
Return type: Method insert() does not return any value, it just modifies the existing list.
Program:
# Python program to demonstrate
# an example of list.insert() method
# list
cities = ['New Delhi', 'Mumbai']
# print the list
print "cities are: ",cities
# insert 'Bangalore' at 0th index
index = 0
cities.insert(index,'Bangalore')
# insert 'Chennai' at 2nd index
index = 2
cities.insert(index, 'Chennai')
# print the updated list
print "cities are: ",cities
Output
cities are: ['New Delhi', 'Mumbai']
cities are: ['Bangalore', 'New Delhi', 'Chennai', 'Mumbai']
Explanation:
- Initially there were two elements in the list ['New Delhi', 'Mumbai'].
- Then, we added two more city names (two more elements) - 1) 'Bangalore' at 0th index and 2) 'Chennai' at 2nd index after adding 'Bangalore' at 0th index, by using following python statements:
# insert 'Bangalore' at 0th index
index = 0
cities.insert(index, 'Bangalore')
# insert 'Chennai' at 2nd index
index = 2
cities.insert(index, 'Chennai')
After inserting 'Bangalore' at 0th index, the list will be ['Bangalore', 'New Delhi', 'Chennai'].
And, then we added 'Chennai' at 2nd index. After inserting 'Chennai' at 2nd index. The list will be ['Bangalore', New Delhi', 'Chennai', 'Mumbai'].
So, it is at our hand, what we have to do? If our requirement is to add an element at the end of the list - use list.append() Method, or if our requirement is to add an element at any index (any specified position) - use list.insert() Method.
ADVERTISEMENT
ADVERTISEMENT