I've been trying to work on a function for an assignment and I'm new to coding. Part of it is to make user insert item to list by entering the desired item and the index without the built-in functions. Currently, I've got the code to replace the item in that index but I can't get it to do what it's supposed to.
Object is the item, and the list is in the main function.
def add(list, obj, index):
nlist = []
print("Your list ", list)
item = input("Insert item: ")
index = int(input("Index: "))
i = 0
for e in list:
if i < index:
nlist.append(e)
i += 1
elif i == index:
nlist.append(obj)
i += 1
elif i > index:
nlist.append(e)
i += 1
print("Your new list ", nlist)
Imagine you have one of those magnetic train sets. like
You want to add a train car after the second one. So you'd break apart the train between index 1
and 2
and then attach it. The front part is everything from 0 to 1 and the second part is everything from 2 till the end.
Luckily, python has a really nice slice syntax: x[i:j]
means slice from i
(inclusive) to j
(exclusive). x[:j]
means slice from the front till j
and x[i:]
means slice from i
till the end.
So we can do
def add(lst, obj, index): return lst[:index] + [obj] + lst[index:]
a = [1,2,3,4,5]
idx = 3
value=[7]
def insert_gen(a,idx,value):
b=a[:idx] + value + a[idx:]
return b
final = insert_gen(a,idx,value)
print(final)
Replace an empty slice with a list containing the object:
lst[index:index] = [obj]
Demo:
>>> for index in range(4):
lst = [0, 1, 2]
lst[index:index] = [9]
print(lst)
[9, 0, 1, 2]
[0, 9, 1, 2]
[0, 1, 9, 2]
[0, 1, 2, 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