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:

  1. index: (Required) The index position where the element has to be inserted.
  2. 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.

Example:
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)
Output
['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.

Example: Insert Tuple and List
mycities = {'Delhi','Chennai'}
favcities = ('Hyderabad','Bangalore')
worldcities = ['Mumbai', 'London', 'New York']
worldcities.insert(1, mycities)
worldcities.insert(3, favcities)

print("Cities: ", cities)
Output
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.

Example: insert()
cities = ['Mumbai', 'London', 'Paris', 'New York']
cities.insert(10, 'Delhi')
print(cities)
Output
['Mumbai', 'London', 'Paris', 'New York', 'Delhi']
Want to check how much you know Python?