The list  is a container data type that represents an ordered collection of element in which each element has an index relative to other elements. Each element in the list   can be accessed using its index.

Lists are mutable meaning the elements can be added into the original list without creating a new list. The insert() method is used to add an element at an arbitrary position in a list.

Using the insert() method

mylist = ['one', 'two', 'four', 'five']

#insert an element at index 2
mylist.insert(2, 'three')

print(mylist)

The syntax of the insert() method is as shown below:

lst.insert(index, item)
index The index at which to insert the item.
item The item to be inserted.

The insert() method adds the item at the specified index and returns None.

cities = ['Ottawa', 'Tokyo', 'Helsinki']

#add a city at index 1
cities.insert(1, 'Manilla')

print(cities)

If the specified index is larger than the  the length of the list, the item is simply appended at the end of the list and if smaller than the smallest valid negative index the item is inserted at the beginning of the list.

mylist = ['five', 'six', 'seven']

#using a large index
mylist.insert(20, 'eight')
print(mylist)

#using a smaller index
mylist.insert(-30, 'four')
print(mylist)

Inserting a tuple

In the following example, we use the insert() method to add a tuple to the list.

mylist = [('PHP', 2), ('Java', 3)]

new_data = (('Python', 0), ('C++', 4), ('HTML', 2))

for i in  new_data:
    mylist.insert(i[1], i)

print(mylist)

In the above example:

  • We have a list of tuples in which the tuples are sorted by the value of their second integer elements.
  • We defined a tuple containing the new tuples to be inserted.
  • We looped through the elements of the new_data tuple inserting each tuple in the list with its second element as the insert index.

Inserting a list

If we have a list of lists, we can use the insert() function to add another list at the specified posltion.

mylist = [[0, 1], [2, 3]]

new_lists = ([4, 5], [6, 7], [8, 9])

for i in new_lists:
   mylist.insert(len(mylist), i)

print(mylist)

In the above example, we have a list which is itself made of lists. We defined a tuple containing the new lists to be inserted then looped through the tuple adding the current element at the end of the list during each iteration.