Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I've been trying to work on a function for an assignment and I'm new to coding. Part of it is to make the user insert the item into the 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.

Here, the main function is the list and the Object is the item

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)

1 Answer

0 votes
by (26.4k points)

Just think you have one of those attractive train sets. like 

You need to add a train vehicle after the subsequent one. So you'd split up the train between index 1 and 2 and afterward connect it. The forward portion (front part) is everything from 0 to 1 and the subsequent part is everything from 2 till the end. 

Fortunately, python has a truly pleasant slice syntax: x[i:j] implies slice from  

i (inclusive) to j (exclusive). x[:j] implies slice from the front till j and x[i:] implies slice from i till the end. 

So we can do

def add(lst, obj, index): return lst[:index] + [obj] + lst[index:]

Want to become a expert in python? Join the python course fast!

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...