Not Understanding Loop Function

Hi. I’m working through “Python Crash Course” on my own but I seem to misunderstand looping. Here is my code:

pizza = ['pepperoni', 'sweet & spicy', 'mushroom']
print(pizza)

for pizza in pizza:
    print(f"\nI sure do love {pizza} pizza.")

friend_pizza = pizza[:]
print(friend_pizza)

When I run the program, I expect the last line to print:

[‘pepperoni’, ‘sweet & spicy’, ‘mushroom’]

Instead, it just prints:

mushroom

If I remove the two middle lines of loop code then the program does what I expect. I don’t understand what it is about the loop code that’s affecting the last two lines.

Hello, @MrRogerSmith, and welcome to Python Software Foundation Discourse!

Here, you are overwriting the pizza variable that you created in the first line of your program:

for pizza in pizza:

Instead, establish a variable with a name other than pizza in the loop header to represent the items within pizza, as follows:

for topping in pizza:
    print(f"\nI sure do love {topping} pizza.")

The variable topping now represents each of the toppings, in turn, as you iterate through pizza. So then, pizza still has its original value as this line is executed, and the slice assignment proceeds as intended:

friend_pizza = pizza[:]

Okay, that makes sense. Thank you for the response, I really appreciate it.

1 Like