5

So I would like to take a list like:

[1, 2, 3, 4]

and then add an item right before the one in position "i". For example, if i = 2 the list would become:

[1, 2, "desired number", 3, 4]

How could I do that in python? Thanks ahead.

ShadowRanger
  • 124,179
  • 11
  • 158
  • 228
Mateus Buarque
  • 205
  • 1
  • 2
  • 8

2 Answers2

6

Insert is a smart choice, you can use list comprehensions (slicing) as well.

Depending on which side of an uneven items list you want to insert you might want to use

lst = [1, 2, 3, 4, 7, 8, 9]

midpoint = len(lst)//2        # for 7 items, after the 3th

lst = lst[0:midpoint] + [5] + lst[midpoint:]  

print (lst) # => [1, 2, 3, 5, 4, 7, 8, 9]

or

lst = [1, 2, 3, 4, 7, 8, 9]

midpoint = len(lst)//2+1      # for 7 items, after the 4th

lst = lst[0:midpoint] + [5] + lst[midpoint:] 

print (lst) # => [1, 2, 3, 4, 5, 7, 8, 9]
Patrick Artner
  • 48,339
  • 8
  • 43
  • 63
2

Just partition the list at the middle, and add the number you want to add between these partitions:

>>> l = [1, 2, 3, 4]
>>> add = 5
>>> l[:len(l)//2] + [add] + l[len(l)//2:]
[1, 2, 5, 3, 4]
RoadRunner
  • 24,495
  • 6
  • 33
  • 71