Python Forum

Full Version: while loop reading list in reverse
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have written some simple code that should read a list and return a result for each item in the list

sandwich_orders = ['jam buttie','pastrami','cheese','pastrami','beef',
                   'chopped pork','pastrami']
finished_orders = []
print("Sorry we have run out of pastrami")
while 'pastrami' in sandwich_orders:
    sandwich_orders.remove ('pastrami')

while sandwich_orders:
    finished_order = sandwich_orders.pop()
    print(f"The {finished_order} is ready for collection")

    finished_orders.append(finished_order)

print (finished_orders)
every thing is reversed i have found i could use lst.reverse() but i dont want to reverse the list just to make it read from beginning to end.

the output comes back as:-

The chopped pork is ready for collection
The beef is ready for collection
The cheese is ready for collection
The jam buttie is ready for collection
['chopped pork', 'beef', 'cheese', 'jam buttie']
[Finished in 0.1s]
Use pop(0) to remove the first item in the list. pop() removes the last.

There are lots of standard ways to manipulate lists, so standard that they have names. One common type of list is called a stack. On a stack you only ever use the last item. You push something onto the stack and pop it back off. You were using a stack. Your last sandwich order was the next order you made.

You want to use a queue. In a queue, the first item in the list is the first item removed. You can still use pop() to remove items from the list, but you need to specify you want to pop from the beginning instead of the end.