Reputation:
I'd like to know the difference between the following two codes using while and for loop in each.
I want to pop elements of the list sandwich_orders
into the list of finished_sandwich
. it seems to work with while loop but not with for loop. What mistake did I make?
sandwich_orders = ['chicken sandwich', 'beef sandwich', 'avocado sandwich', 'pork sandwich']
finished_sandwich = []
while sandwich_orders:
cur_sandwich = sandwich_orders.pop()
finished_sandwich.append(cur_sandwich)
print (finished_sandwich)
for cur_sandwich in sandwich_orders:
cur_sandwich = sandwich_orders.pop()
finished_sandwich.append(cur_sandwich)
print (finished_sandwich)
Upvotes: 0
Views: 79
Reputation: 2084
After while
loop, your variable sandwich_orders
becomes empty as you are popping elements from it during the while
loop. So you need to reinitialize it.Try in this way
sandwich_orders = ['chicken sandwich', 'beef sandwich', 'avocado sandwich', 'pork sandwich']
finished_sandwich = []
while sandwich_orders:
cur_sandwich = sandwich_orders.pop()
finished_sandwich.append(cur_sandwich)
print (finished_sandwich)
sandwich_orders = ['chicken sandwich', 'beef sandwich', 'avocado sandwich', 'pork sandwich']
finished_sandwich= []
for cur_sandwich in sandwich_orders:
finished_sandwich.append(cur_sandwich)
print (finished_sandwich)
Upvotes: 0
Reputation: 26925
The for loop could be written thus:
sandwich_orders = ['chicken sandwich', 'beef sandwich', 'avocado sandwich', 'pork sandwich']
finished_sandwich = []
for _ in sandwich_orders[:]:
finished_sandwich.append(sandwich_orders.pop())
...or, to retain the order of the original list:
for _ in sandwich_orders[:]:
finished_sandwich.insert(0, sandwich_orders.pop())
...or, to avoid loops altogether:
finished_sandwich = sandwich_orders[:]
Upvotes: 1