Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

Abdalla Kassim
Abdalla Kassim
446 Points

Using index 0 to insert milk and creamer into shopping_list_3.py

If you use index 0 to insert milk and creamer into shopping_list_3.py you get this:

1: creamer
2: apples
3: bananas
4: strawberries
5: milk
6: yogurt

Could anyone explain to me why?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

The progam as written assumes the user would enter a 1-indexed value, but doesn't check if a value is zero or negative. Python let's you use negative indexes to mean "from the end of the list". So when you enter a "0", the program inserts two items. The first at index -1 (that's your zero - 1), then the second item by incrementing the index from -1 to 0. Looking at an example:

Given a list ["a", "b", "c", "d"], insert two items "m1, z" at "position 0". Since the program substracts 1 from the starting position, the starting index will be -1:

# Make a list
In [19]: the_list = ["a", "b", "c", "d"]
# Insert first item "m1" at index -1
In [20]: the_list.insert(-1, "m1")
# review list
In [21]: the_list
Out[21]: ['a', 'b', 'c', 'm1', 'd']
# Insert second item "z" at index 0 (-1 + 1)
In [22]: the_list.insert(0, "z")
# review list
In [23]: the_list
Out[23]: ['z', 'a', 'b', 'c', 'm1', 'd']

In your case, milk is inserted at index -1 and creamer is inserted at index '0'.