0

I was trying to answer an exercise in a beginner's guide to python book. I tried using the while loop first and got the right output, but I experimented by using the for loop, and got an unexpected output. Why the difference in results?

sandwich_orders = ['mushrooom sandwich','cheese sandwich','jalapeno sandwich','bacon sandwich','pastrami','pastrami','pastrami']
finished_sandwiches = []

for sandwich in sandwich_orders:
    finished_sandwich = sandwich_orders.pop()
    if finished_sandwich != 'pastrami':
        print("I made your " + finished_sandwich + ".")
        finished_sandwiches.append(finished_sandwich)
    else:
        print("The deli has run out of pastrami.")


print("\nFinished sandwiches: ")
for sandwich in finished_sandwiches:
    print("\t" + sandwich)
print("\n")
while 'pastrami' in sandwich_orders:
    sandwich_orders.remove('pastrami')

Output (incorrect):

The deli has run out of pastrami.
The deli has run out of pastrami.
The deli has run out of pastrami.
I made your bacon sandwich.

Finished sandwiches: 
    bacon sandwich

Correct output:

I made your mushroom sandwich.
I made your jalapeno sandwich.
The deli has run out of pastrami.
The deli has run out of pastrami.
I made your cheese sandwich.
The deli has run out of pastrami.
I made your bacon sandwich.

Finished sandwiches: 
    mushroom sandwich
    jalapeno sandwich
    cheese sandwich
    bacon sandwich
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Please [edit] your question and post a [mre]. We can't run this code as-is. – MattDMo Dec 25 '21 at 23:33
  • Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Silvio Mayolo Dec 25 '21 at 23:34

1 Answers1

0

Don't modify a list while iterating over it.

Here is a fixed version:

sandwich_orders = ['mushrooom sandwich','cheese sandwich','jalapeno sandwich','bacon sandwich','pastrami','pastrami','pastrami']
finished_sandwiches = []

for sandwich in sandwich_orders:
    if sandwich != 'pastrami':
        print("I made your " + sandwich + ".")
        finished_sandwiches.append(sandwich)
    else:
        print("The deli has run out of pastrami.")

Output:

I made your mushrooom sandwich.
I made your cheese sandwich.
I made your jalapeno sandwich.
I made your bacon sandwich.
The deli has run out of pastrami.
The deli has run out of pastrami.
The deli has run out of pastrami.
mozway
  • 194,879
  • 13
  • 39
  • 75