The insert() method inserts an element to the list at a given index.
The syntax of insert() method is
list.insert(index, element)
The insert() function takes two parameters:
The insert() method only inserts the element to the list. It doesn’t return anything; returns None
.
# 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']
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