Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 610
Lucas Johns Avatar asked Apr 17 '17 21:04

Lucas Johns


3 Answers

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") 
like image 152
Patrick Haugh Avatar answered Oct 28 '22 10:10

Patrick Haugh


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()
    ...
like image 31
Rolo787 Avatar answered Oct 28 '22 08:10

Rolo787


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."

like image 36
J. Olsson Avatar answered Oct 28 '22 09:10

J. Olsson