10

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
  • 143,180
  • 12
  • 188
  • 271
Mateus Buarque
  • 255
  • 1
  • 2
  • 9

2 Answers2

9

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
  • 50,409
  • 9
  • 43
  • 69
3

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
  • 25,803
  • 6
  • 42
  • 75