How does python know? ex38

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.")

Coldsun1

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

that’s what I think is happening
json

2 Likes

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.")

Thank you!

@coldsun1
From one beginner to another :wink: :slightly_smiling_face:

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.

Take care,
Danny

1 Like

Your reply is clear. Thank you for the help! :grinning:

2 Likes