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
Why "spot =+ 1"?
Hi, two questions about the usage of "spot =+ 1":
Firstly, if the purpose of the "spot" variable is to capture a new location within which the user wants to index an item every time it's looped through, why do we want to add a 1 to the variable every time?
Secondly, the way I interpret this code, every time the script loops through, it should reset the value of spot so that it equals the number entered as an index:
"spot = int(index) - 1"
e.g. First loop: spot = "given index location" - 1 to provide "desired index location". spot is referenced to place the item in the list 1 is added to spot
e.g. Second loop: spot = "given index location" - 1 to provide "desired index location" etc..
Why is the value written at the end of the first loop not overwritten when spot is given a new value in the second loop?
Apologies if this is a stupid question, I'm just struggling to get my head around it.
Chris FreemanTreehouse Moderator 68,423 Points
Given the following code:
spot = int(index) - 1
for item in new_list:
spot += 1
spot is set to the the integer value of
index minus 1. Because users like to interact in a list indexes starting at 1, 2, 3... and the
spot will hold the "minus 1" value to interact with the
shopping_list indexes starting at 0, 1, 2....
For the first iteration of the loop
spot equals the user's desired insert location. The
.insert() method puts the first
new_list at that index and all following shopping list elements are shifted over. Before the second loop starts
spot is incremented by 1 so that the insertion point is move along to follow the item just inserted.
For the second loop, the next item from
new_list is assigned to
item and the loop begins. The insertion takes place at the location following the previous insertion.
spot is incremented again in preparation for the third loop.
spot was not incremented, all insertions would happen at "index minus 1", which would effectively reverse the order the user listed in the cases where more than one item in
spot does not get reinitialized to "index - 1" because that statement is previous to and not in the loop.