Click for All Topics
.insert()
method with an index position and an element then first it will check the index position whether it is in valid range(smaller than length of list) or not if it is in range then it right shifts all element to free up space of given index position and then insert the element at given index position if index is not in valid range and index is positive then it will insert element at last and if given index value is negative then it will insert element at beginning of the list..insert()
method takes O(n) time complexity where n is the number of elements.
Syntax –
list.insert(index,element)
Parameter –
Example – insert 1 at index 0 in a list
my_list=[2,3,4,5,6]
print("Original list:",my_list)
my_list.insert(0,1)
print("Original list after inserting 1 at index 0")
print(my_list)
# Output -
# Original list: [2, 3, 4, 5, 6]
# Original list after inserting 1 at index 0
# [1, 2, 3, 4, 5, 6]
.insert()
method.
Example 2- insert a list to the list at specified position
my_list=['Hello', 'everyone', 'this','is']
my_list1=['edSlash', 'official']
print("Original list:",my_list)
my_list.insert(4,my_list1)
print("Original list after inserting another list:")
print(my_list)
# Output -
# Original list: ['Hello', 'everyone', 'this', 'is']
# Original list after inserting another list:
# ['Hello', 'everyone', 'this', 'is', ['edSlash', 'official']]
Example 3- insert element outside of the list range
lst=[10,20,30,40,50]
print("Original list:",lst)
lst.insert(6,60) # will insert 60 at the end
print("Modified list:",lst)
# Output -
# Original list: [10, 20, 30, 40, 50]
# Modified list: [10, 20, 30, 40, 50, 60]
Example 4- insert a string to the list at specified position
my_list=['a','b','d','e','f']
print("Original list", my_list)
my_list.insert(2,'c')
print("Modified original list:",my_list)
# Output -
# Original list ['a', 'b', 'd', 'e', 'f']
# Modified original list: ['a', 'b', 'c', 'd', 'e', 'f']
insert() | append() |
---|---|
It is used to insert an element to a list at specified position. | It adds an element to the end of the list |
It takes two arguments the index position where element has to be inserted and the element itself. | It takes only element as an argument. |
The time complexity of insert method is O(n) | The time complexity of append method is O(1). |
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India