Oct-03-2018, 08:27 PM
The for loop is basically syntactic sugar for a while loop, and this is one of the ways where the underlying method makes itself visible. The for loop keeps track of what position it's currently at in the list, and increases that each time. So if you change the list while looping over it, you get weird results (like you're seeing).
Sort of like this:
Sort of like this:
>>> guests = ['Geoff', 'Colin', 'David', 'Adolf', 'Charles', 'Fred'] >>> index = 0 >>> while index < len(guests): ... current = guests[index] ... index += 1 ... removed = guests.pop() ... print(f"Iteration: {index}\tRemoved: {removed}\tRemaining: {guests}") ... Iteration: 1 Removed: Fred Remaining: ['Geoff', 'Colin', 'David', 'Adolf', 'Charles'] Iteration: 2 Removed: Charles Remaining: ['Geoff', 'Colin', 'David', 'Adolf'] Iteration: 3 Removed: Adolf Remaining: ['Geoff', 'Colin', 'David']