-5

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!

4
  • You're changing the positions your iterators refer to. We have duplicates for this -- looking for one.CommentedApr 12 at 12:23
  • How to remove items from a list while iterating focuses on solutions -- not using it as a duplicate because your goal is an explanation of the problem.CommentedApr 12 at 12:24
  • The question Modifying a list while iterating over it - why not? has some faults, but despite being poorly asked (providing an example that doesn't actually constitute what the title is asking about) it has answers that are directly on-point and applicable to explaining the cause of the behavior at hand. In particular see this one and this one.CommentedApr 12 at 12:27
  • thanks Mr. Charles Duffy and Mr. Karl Knechtel
    – LORD V
    CommentedApr 12 at 14:46

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.