Popping items from a list using a loop

I am trying to write a for loop in python to pop out all the items in a list but two, so I tried this:

guest = ['john', 'phil', 'andy', 'mark', 'frank', 'joe']

for people in guest:
  popped_guest = guest.pop()
  print("I am sorry " + popped_guest + " I can no longer invite you to dinner")

and this is what I get when I run it:

I am sorry joe I can no longer invite you to dinner

I am sorry frank I can no longer invite you to dinner

I am sorry mark I can no longer invite you to dinner

So it only pops the 3 but is there a way to get it to pop 4 of the 6? I tried adding an if statement:

guest = ['john', 'phil', 'andy', 'mark', 'frank', 'joe']

for people in guest:
  if people > guest[1]:
    popped_guest = guest.pop()
    print("I am sorry " + popped_guest + " I can no longer invite you to dinner")

I would have thought since that ‘phil’ would be 1 that it would pop the last 4 but when I ran the program it returned nothing. So is it possible to do in one for loop?

Answer

If you want to pop 4 things, then just count to 4

for _ in range(4):
    popped_guest = guest.pop()
    print("I am sorry " + popped_guest + " I can no longer invite you to dinner") 

Leave a Reply

Your email address will not be published. Required fields are marked *