Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (Retired) Lists Redux Shopping List Take Three

The code is buggy when the index is entered as 0

The code runs fine for inserting elements at all indexes except 0. When I enter 0 , and if I have say 3 items in the list it just puts the element in position 2 , If i have 6 items and I enter 0 it puts the item in position 5.

Kenneth at one point in the video was about to enter the index 0 and then he changed his mind and entered 1. I wished he would have entered 0.

Has anyone else tried with 0 ?

2 Answers

It doesn't work with zero by design. Notice the definition of spot,

        if index:
            spot = int(index) - 1
            for item in new_list:
                shopping_list.insert(spot, item.strip())
                spot += 1

Kenneth writes the code to take whatever index the user gives and decrement it by one so that the details of Python's list index syntax are hidden from the user. This way when the user enters "1" for "index" the item is placed at the beginning of the list as expected.

Using zero as the first index in an array (in Python, lists are implemented as arrays in the underlying C code) is an idiosyncrasy of programming languages and not necessarily intuitive to the nonprogrammer. I think the average person would assume that the first item in a list is in the 1(st) position - so Kenneth's design choice seems sound to me.

Also, notice that the first argument passed to the .insert() method indicates the "index of the element before which to insert" (from the Python docs). This is why an input of 0, decremented to -1, ends up before the last item in the list.

TL;DR: I wouldn't call this a bug, since most users wouldn't think to give 0 as a position. But perhaps we could add some code to make sure that the user can only enter values larger than zero. Or maybe force an input of zero to also go to the beginning of the list rather than wrapping around to the end.

Hope that helps!

YES It's also the case when the index is greater than the total list items so i had to make some tweaks to mine,

shopping_list = []

def show_help():
    print("Seperate each item with a comma")
    print("Type 'DONE' to quit 'SHOW' to see the current list and 'HELP' to get this message")

def show_list():
    count =1
    for item in shopping_list:
        print('{}: {}'.format(count, item))
        count +=1
    main()

print("Give me a list of things you want to shop for ?")
show_help()

def main():
        while True:
            new_stuff = input(">: ")

            if new_stuff == "DONE":
                print("\nHeres Your list of items:\n")
                show_list()
                break

            elif new_stuff == "HELP":
                show_help()
                continue
            elif new_stuff == "SHOW":
                show_list()
                continue
            else:
                new_list = new_stuff.split(",")
                index = input("Add this at a certian spot? Press enter for the end of the list, "
                              "Or give me a number. Currently {} items in the list.".format(
                                  len(shopping_list)))



                if index:
                    while index:
                         try:
                            spot = int(index) - 1
                            if (spot - 1) > len(shopping_list):
                                    for item in new_list:
                                        shopping_list.append(item.strip())
                                    print("Sorry the list only has {}".format(len(shopping_list)))
                                    num = input("Press Enter to add more items or SHOW to view list")

                                    if num == "SHOW":
                                        show_list()
                                    else:
                                        main()

                            else:
                                for item in new_list:
                                    shopping_list.insert(spot, item.strip())
                                    spot += 1
                         except ValueError:
                                 index = input("{} is not a number. Please try again. " 
                                                "\nEnter a valid number " 
                                              "or press enter for end of the list: ".format(index))
                                 if index:
                                     continue
                                 else:
                                     for item in new_list:
                                         shopping_list.append(item.strip())
                                     break
                else:
                    for item in new_list:
                        shopping_list.append(item.strip())



main()