The insert() function in python helps to insert the given element into the specified index of the list.
list.insert(i, elem) #where element may be string, number, object etc.
The insert() function takes two parameters. If the element is inserted in the specified index, all the remaining elements are shifted to the right.
Parameter | Description | Required / Optional |
---|---|---|
index | the index where the element needs to be inserted | Required |
element | the element to be inserted in the list | Required |
This method doesn't return any value. It modifies the original list by adding elements to it. If the given index is zero the element is inserted at the first position, if it index is two the element is inserted after the second element that is its position will be the third position.
# alphabets list
alphabets = ['a', 'b', 'd', 'e']
# 'c' is inserted at index 2
# the position of 'c' will be 3rd
vowel.insert(2, 'c')
print('Updated List:', alphabets)
Output:
Updated List: ['a', 'b', 'c', 'd', 'e']
firs_list = [{1, 2}, [5, 6, 7]]
# ex tuple
ex_tuple = (3, 4)
# inserting a tuple to the list
firs_list.insert(1, ex_tuple)
print('Final List:', firs_list)
Output:
Final List: [{1, 2}, (3, 4), [5, 6, 7]]