Python List insert() - Insert Element At Specified Position
Insert an item at a given position.
The list.insert()
method is used to insert a value at a given position in the list.
Syntax:
list.insert(index, value)
Parameters:
- index: (Required) The index position where the element has to be inserted.
- value: (Required) The value that has to be added. It can be of any type (string, integer, list, tuple, etc.).
Return type:
No return value.
The following example demonstrates the insert()
method.
cities = ['Mumbai', 'London', 'Paris', 'New York']
cities.insert(0, 'New Delhi') # inserts at 0 index (first element)
print(cities)
cities.insert(2, 'Chicago') # inserts at 2nd index
print(cities)
['New Delhi', 'Mumbai', 'London', 'Paris', 'New York']
['New Delhi', 'Mumbai', 'Chicago', 'London', 'Paris', 'New York']
The insert method can also insert set and tuples into a list. You can also add dictionaries to a list also.
mycities = {'Delhi','Chennai'}
favcities = ('Hyderabad','Bangalore')
worldcities = ['Mumbai', 'London', 'New York']
worldcities.insert(1, mycities)
worldcities.insert(3, favcities)
print("Cities: ", cities)
Cities: ['Mumbai', {'Delhi', 'Chennai'}, 'London', ('Hyderabad', 'Bangalore'), 'New York']
When an index is passed that is greater than the length of the list, the insert() method inserts the element at the end of the list.
cities = ['Mumbai', 'London', 'Paris', 'New York']
cities.insert(10, 'Delhi')
print(cities)
['Mumbai', 'London', 'Paris', 'New York', 'Delhi']