Ask coding questions

← Back to all posts
Working with While loops to remove an occurance
kess (2)

Lines 19 down.
I wrote code to use a while loop to remove all occurrences of a specific string and print the remainder of the content in the list. This code works however searching for a more efficient way to move the contents from one list to the next instead of copying them over.
I would like the contents of sandwich_orders be placed in finished_orders. I tried using the pop() method instead of remove but the finished_order list would keep the occurrences of pastrami . Any suggestions

#Make a list called sandwich_orders and an empty list
sandwich_orders = ['tuna','pastrami', 'egg', 'ham', 'cheese', 'pastrami','pastrami']
finished_orders = []

print("\nThe deli had run out of Pastrami. No Pastrami Sandwiches can be made at this time.")

#Create a while loop that searches for all occurances of 'pastrami' in the sandwich_order list, when found remove all occurances from the list.

while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')

Mirror the sandwich list to the finished list.

finished_orders = sandwich_orders

Loop through list to print message when sandwich is finished.

for sandwich in finished_orders:
print("You " + sandwich.title() + " sandwich is ready!")

Commentshotnewtop
LeonDoesCode (393)

There is another way, but I'm not sure if it is more efficient, I believe it is though.

finished_orders = list(filter(('pastrami').__ne__, sandwich_orders))

The __ne__ is just like writing !=, but that would be a bit more long in this case.