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

Welby Obeng
Welby Obeng
20,340 Points

why is spot += 1 needed?

why spot += 1 needed in

    if index:   #if a number is entered
      spot = int(index) - 1 #change string to an integer
      for item in new_list: # for all items in new_list created from newstuff
          shopping_list.insert(spot, item.strip()) # insert into shopping list the item at a certain spot
          spot += 1

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Since we might have more than one thing in our new list, we need to increment the spot that we're inserting them. Otherwise we'd end up with them inserted in reverse order.

Welby Obeng
Welby Obeng
20,340 Points

hmmm still a little confused...can you give me an example please

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Sure.

>>> my_list = [1, 2, 3]
>>> my_new_list = [4, 5, 6]
>>> spot = 1
>>> for thing in my_new_list:
...     my_list.insert(spot, thing)
>>> my_list
[1, 6, 5, 4, 2, 3]

Since we didn't increment spot, we inserted into index 1 every single time. That pushes the last thing that we inserted, plus everything that was already past it, further back. That results in our new list showing up in reverse.