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?
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")
Your for
loop discontinues after its 3rd iteration since that is how many elements are left in guest
after having popped the previous ones. You can potentially use a while loop to continuously pop elements until the list remains with just 2.
while len(guest) > 2:
popped_guest = guest.pop()
...
As mentioned, your code is not doing at all what you think it is, because you are popping elements out of the list while actively iterating through it. I would say "a much better coding practice would be to duplicate the list to pop out of," but it's not a "better" practice - your way simply doesn't work at all how you want it to, it will always pop out the first half of your list.
I would ask myself "How do I specify who gets popped in my current iteration," and "Where do I set how many people get popped in my current iteration". The answer to both questions appears to be "I don't."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With