6

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)
7
  • 1
    how about nlist+[e] Commented Mar 21, 2017 at 19:54
  • 1
    It looks like you get the the object and the index passed as arguments, so you probably shouldnt use input here. Commented Mar 21, 2017 at 19:55
  • Seriously, you can't use append? That will force you to use some other, less efficient method that doesn't really add to understanding at all. Commented Mar 21, 2017 at 19:56
  • 1
    you could concat the list into [:index] + desired item + [index:] Commented Mar 21, 2017 at 19:57
  • 2
    @juanpa.arrivillaga Unless it's a contrived exercise to teach slicing. Which is still a terrible assignment, but if you're trying to get them to use slicing... Commented Mar 21, 2017 at 19:57

3 Answers 3

15

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:]
Sign up to request clarification or add additional context in comments.

2 Comments

If you are allowed to mutate the list, lst[x:x] = [obj] inserts obj just prior to element x. x = 0 lets you prepend, and lst[-1:] (the exception) appends.
@chepner Doing lst[-1:] = [obj] will replace the last element with obj rather than appending it... On the other hand, lst[len(lst):] = [obj] will append
1
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)

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.