i have a list
my_list= [1,2,4,5]
i want to add 3 to the list, in between the 2 and the 4 so the list becomes:
[1,2,3,4,5]
how do i do this?
i have a list
my_list= [1,2,4,5]
i want to add 3 to the list, in between the 2 and the 4 so the list becomes:
[1,2,3,4,5]
how do i do this?
Use insert method to add element at specific index.
Syntax : list.insert(i, elem)
my_list.insert(2, 3) # inserting 3 at index 2.
to know more about insert method Python List insert()
With insert()
.
>>> my_list= [1,2,4,5]
>>> my_list.insert(2, 3)
>>> my_list
[1, 2, 3, 4, 5]
>>>
if you don't know the index of 2(lower limit) you can use
>>> index_of_2 = my_list.index(2) #gives you index of 2(lower limit)
>>> element_to_insert = 3
>>> my_list.insert(index_of_2 + 1, element_to_insert)