I encountered an issue where I intended to limit the invitations to only two people using a for loop. However, the code ends up leaving three people in the list instead of two. Here's the code I'm using:
print('Unfortunately you are allowed to invite only two people') people_to_invite = ['leonardo da vinci', 'jorden b peterson', 'jeffrey kaplan', 'joshua meyer', 'harold', 'james bon', 'jakie chan'] for people in people_to_invite: if len(people_to_invite) > 2: place_holder = people_to_invite.pop() else: break for person in people_to_invite: print(f">>Dear {person.title()}, I would like to invite you to a dinner gathering at my home on Saturday,\nthe 15th, at 7 PM. It would be wonderful to have you with us!")
This part of the code is meant to remove people until only two remain:
for people in people_to_invite: if len(people_to_invite) > 2: place_holder = people_to_invite.pop() else: break
However, it doesn't work as expected. The result is that three people remain in the list. I know I can use a while loop instead, like this:
while len(people_to_invite) > 2: people_to_invite.pop()
Or, I can modify the logic using:
for people in range(len(people_to_invite) - 2): place_holder = people_to_invite.pop()
But I’m curious—what exactly is causing the issue with the original for loop? Is there an underlying limitation of the for loop when modifying a list during iteration?
Any clarification would be greatly appreciated!