-1

Ok, look. I know this is a stupid question, but it has been bothering me for quite some time now. I am an inexperienced programmer working with Python. I am just starting to build simple programs of my own. When completing a simple exercise, I decided to use a for loop.

The loop is supposed to run through the guest list, and print a message for each guest. Once the message is printed, the loop is supposed to remove the current guest. By the end of the loop, the list should be empty. When examining my output in my terminal, I noticed there was still a name in the list.

My question is obvious; why won't my loop remove the last value from the list?

Below is the code I wrote for the loop:

for guest in guest_list:

    guest_message = f"\nHello, {guest.title()}! Thank you for coming. Dinner will be served shortly, but in the meantime, please have a seat.\n"
    print(guest_message)
    guest_list.remove(guest)

print(guest_list)

This was the output:

Hello, Mike! Thank you for coming. Dinner will be served shortly, but in the meantime, please have a seat.

['jane']

As you can tell, there were supposed to be two messages instead of one, and the list should by now, be empty.

Thank you for your time.

pavel
  • 2,839
  • 2
  • 21
  • 33
Collin
  • 1
  • How to solve https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating and the reasoning: https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list – Andrew Ryan May 26 '22 at 01:47
  • 1
    You are having trouble because you are modifying the list as you're iterating through it which is never a good idea. – pavel May 26 '22 at 01:48
  • Recommend to try this Visual platform - https://pythontutor.com/ To see what's been running in each step. – Daniel Hao May 26 '22 at 01:53
  • You can try to use `while` loop then iterating and removing item in array until the array is empty to stop the loop. – DrakeLiam May 26 '22 at 01:56
  • Thank you all for your help. I really appreciate it. – Collin May 27 '22 at 18:42

0 Answers0