Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert item to list without insert() or append() Python

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)
like image 576
SE Chou Avatar asked Mar 21 '17 19:03

SE Chou


Video Answer


3 Answers

Imagine you have one of those magnetic train sets. like enter image description here

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:]
like image 66
marisbest2 Avatar answered Oct 24 '22 09:10

marisbest2


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)
like image 1
sangam92 Avatar answered Oct 24 '22 11:10

sangam92


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]
like image 1
Kelly Bundy Avatar answered Oct 24 '22 09:10

Kelly Bundy