Python List Methods Tutorial: Python List Insert()

The insert() method inserts an element to the list at a given index.
The syntax of insert() method is

list.insert(index, element)

insert() Parameters

The insert() function takes two parameters:

  • index - position where an element needs to be inserted
  • element - this is the element to be inserted in the list

Return Value from insert()

The insert() method only inserts the element to the list. It doesn’t return anything; returns None.

Example 1: Inserting Element to List

# vowel list
vowel = ['a', 'e', 'i', 'u']

# inserting element to list at 4th position
vowel.insert(3, 'o')

print('Updated List: ', vowel)

When you run the program, the output will be:

Updated List:  ['a', 'e', 'i', 'o', 'u']

Example 2: Inserting a Tuple (as an Element) to the List

mixed_list = [{1, 2}, [5, 6, 7]]

# number tuple
number_tuple = (3, 4)

# inserting tuple to the list
mixed_list.insert(1, number_tuple)

print('Updated List: ', mixed_list)

When you run the program, the output will be:

Updated List:  [{1, 2}, (3, 4), [5, 6, 7]]

It is important to note that the index in Python starts from 0, not 1.

If you have to insert an element at the 4th place, you have to pass 3 as an index. Similarly, if you have to insert an element at the 2nd place, you have to use 1 as an index.

#python

Python List Methods Tutorial: Python List Insert()
1.55 GEEK