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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With