insert() method in Python Lists can be used to insert an element at the specified position of the list. This element can be of any type like integer, string, boolean, list etc.
The insert() method modifies the specified list by adding the element at the specified position of the list, however, it does returns ‘None’ value in all cases.
Syntax
list.insert(i, ele)
i: position where element needs to be added in a list (mandatory)
ele: element to be added (mandatory)
l = [1, 3, 5, 2, 8, 3]
print(l.insert(1, 10)) # returns 'None'
print(l) # returns modified list where 10 is added as second element (index 1)
O/P
None
[1, 10, 3, 5, 2, 8, 3]
Please note that, previous value at first index was not lost but shifted towards right.
If the position specified does not exists, then, that element is added at the end of the list.
For example, if the length of a list is 5 and you ask to add the element at the 10th position. Since this index does not exists, the specified element will added the end of the list.
Below code explains this
l = [1, 3, 5, 2, 8, 3]
print(l.insert(10, 10)) # returns 'None'
print(l) # returns modified list
O/P
None
[1, 3, 5, 2, 8, 3, 10]
That’s all here.
