The insert method
The insert method adds an element to the list before the specified index. In the first parameter, we specify the index before which the element should be placed, in the second parameter - the element we want to add to the list.
Syntax
list.insert(index of what to add)
Example
Let's add the element '12' at position 2 in our list:
lst = ['ab', 'cd', 'ef', 'gh']
lst.insert(2, '12')
print(lst)
print(lst.index('12'))
Result of code execution:
['ab', 'cd', '12', 'ef', 'gh']
2
Example
Now let's add an element to the end of the list:
lst = ['ab', 'cd', 'ef', 'gh']
lst.insert(-1, '12')
print(lst)
print(lst.index('12'))
As can be seen from the result obtained, the element was added not to the end of the list, but before the last element:
['ab', 'cd', 'ef', '12', 'gh']
3
See also
-
method
append,
which adds an element to the end of a list -
method
pop,
which removes an element by its index -
method
index,
which searches for an element in a list and returns its index -
method
count,
which returns the number of times an element occurs in a list -
method
clear,
which removes all elements of a list