-3

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?

Vedik vk
  • 31
  • 1
  • 6
  • 2
    Does this answer your question? [Insert an element at specific index in a list and return updated list](https://stackoverflow.com/questions/14895599/insert-an-element-at-specific-index-in-a-list-and-return-updated-list) – Abhishek Bhagate Jun 26 '20 at 20:38

3 Answers3

3

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()

Tom
  • 8,310
  • 2
  • 16
  • 36
shivam sharma
  • 121
  • 1
  • 4
1

With insert().

>>> my_list= [1,2,4,5]
>>> my_list.insert(2, 3)
>>> my_list
[1, 2, 3, 4, 5]
>>>
kichik
  • 33,220
  • 7
  • 94
  • 114
0

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)
VIPK
  • 9
  • 1