I changed the while-loop to a for-loop but it still seems to know that i want it to stop at 10 items. How does it know?
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait there are not 10 things in that list. Let's fix that.")
stuff = ten_things.split(' ')
more_stuff = ['Day', 'Night', 'Song', 'Frisbee', 'Corn', 'Banana', 'Girl', 'Boy']
for x in more_stuff:
next_one = more_stuff.pop()
print("Adding: ", next_one)
stuff.append(next_one)
print(f"there are {len(stuff)} items now.")
your for-loop is walking through more_stuff one item at a time from the beginning but you are also shortening more_stuff with the .pop() function, effectively you are meeting in the middle as the loop has got to the end of the now shortened more_stuff
Ahhh okay i get it. I should have used the stuff variable and then put a limiter in the for statement.
Like so:
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait there are not 10 things in that list. Let's fix that.")
stuff = ten_things.split(' ')
more_stuff = ['Day', 'Night', 'Song', 'Frisbee', 'Corn', 'Banana', 'Girl', 'Boy']
for x in stuff:
if len(stuff) >= 10:
break
next_one = more_stuff.pop()
print("Adding: ", next_one)
stuff.append(next_one)
print(f"there are {len(stuff)} items now.")
As our colleague just said, youâre âpoppingâ items from your âmore_stuffâ list to make them values assigned to your ânext_oneâ variable. At the same time, your âxâ iterator variable is moving through the same list one position at the time (or per iteration). The end state comes when âxâ comes to the âFrisbeeâ element - at that point âCornâ is âpoppedâ, or cut out of the list and thatâs where the For loop ends becuase thereâs no next element for âxâ to move to. At that moment, exactly four elements had been âpoppedâ out, namely: âBoyâ, âGirlâ, âBananaâ, and âCornâ in that order.
So, those four elements plus the ones in âstuffâ list (6 of them), make your final ten-elements list âstuffâ.
I donât know if Iâm completely clear, but this should be the correct interpretation of your code.