Evaluating items from a list using a loop

I'm trying to write a for loop in python to pull out all the elements 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:

I'm sorry that I can't invite you to dinner anymore

I'm sorry, I can't invite you to dinner anymore

I'm sorry that I can no longer invite you to dinner

So, it only pops 3, but is there a way to make it pop 4 of 6? I tried to add 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 this "phil" would be 1, that it would appear the last 4, but when I ran the program, it didn't return anything. So is it possible to do it in one cycle?

+3


source to share


5 answers


If you want to post 4 things, 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") 

      

+6


source


Your loop for

breaks after the 3rd iteration as this is the number of items left in guest

after they pushed the previous ones out. You can potentially use a while loop to continuously retrieve items until only 2 are left in the list.



while len(guest) > 2:
    popped_guest = guest.pop()
    ...

      

+3


source


As mentioned, your code does not do what you think it does at all, because you are dropping items off the list while actively repeating it. I would say "a much better coding practice would be to duplicate a list to pop out of", but that is not a "best" practice - your path just doesn't work at all the way you want it to, it will always pop out in the first half of your list.

I would ask myself, "How do I indicate who is in my current iteration" and "Where can I set how many people are in my current iteration." The answer to both questions seems to be "I don't."

+1


source


The reason for this behavior is that when you used a for loop in Python, it actually scans the list by its index number. So when you iterate over the list and mutate it at the same time, you might be missing multiple items. It is best to redo the copy of the list by going over the original.

0


source


invite = ['Pankaj', 'Deepak', 'Nischey', 'Ram', 'Martin', 'Gopal']

for item in invite:
    if invite.index(item) > 1:
        popped_guest = invite.pop()
        print("Sorry you are not invited " + popped_guest)
    else:
        print("you are invited " + item)

      

0


source







All Articles