Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding items in the middle of a list in python [duplicate]

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.

like image 964
Mateus Buarque Avatar asked Feb 01 '18 11:02

Mateus Buarque


1 Answers

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]
like image 79
Patrick Artner Avatar answered Sep 19 '22 14:09

Patrick Artner