0

I have written a code with a list of invitees but as I am popping the uninvited guests from the list, the for loop stops running at index 3 and instead of first two people in the list, first four get invited. please point out what's wrong. Thanks

invitees = ["name1","name2","name3","name4","name5","name6"]
print(invitees)
print("Sorry guys change in plans, cannot invite all of you guys")
#using pop() to invite only two from the list of invitees
for invitee in invitees:
    if len(invitees)>2:
        popped_invitee = invitees.pop()
        print(f"Sorry! {popped_invitee.title()}, you are uninvited")
        print(invitees)
#the univited get a message and also the invited
for invitee in invitees:
    print(f"hey! {invitee.title()}, you are still invited")

2 Answers2

0

Do not attempt to modify lists that you're currently iterating over! That way lies madness. See this answer by some incredibly intelligent and good-looking poster as to why this is a bad idea :-)

You can actually achieve the same result with something like:

while len(invitees) > 2:
    popped_invitee = invitees[0]
    print(f"Sorry! {popped_invitee.title()}, you are uninvited")
    invitees = invitees[1:]
print(invitees) # should now have two or fewer items

or, better, since you modify the list only once:

if len(invitees) > 2:
    popped_invitees = invitees[:-2]
    invitees = invitees[-2:]
    for popped_invitee in popped_invitees:
        print(f"Sorry! {popped_invitee.title()}, you are uninvited")
print(invitees) # should now have two or fewer items
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
-1
In [36]: a = [1,2,3,4,5]                                                                                                                                                                                           

In [37]: a.pop(0)                                                                                                                                                                                                  
Out[37]: 1
mathtick
  • 6,487
  • 13
  • 56
  • 101