Python Forum
while loop reading list in reverse
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
while loop reading list in reverse
#1
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]
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  trouble reading string/module from excel as a list popular_dog 0 414 Oct-04-2023, 01:07 PM
Last Post: popular_dog
  Reading list items without brackets and quotes jesse68 6 4,607 Jan-14-2022, 07:07 PM
Last Post: jesse68
  Loop reading csv file problem faustineaiden 1 1,561 Dec-11-2021, 08:40 AM
Last Post: ibreeden
  Question about List.reverse() method tomliuwhite 1 1,334 Dec-07-2021, 08:20 AM
Last Post: ndc85430
  I am trying to reverse a string using loop codinglearner 4 2,158 Sep-28-2021, 10:46 PM
Last Post: Pedroski55
  Reading data to python: turn into list or dataframe hhchenfx 2 5,352 Jun-01-2021, 10:28 AM
Last Post: Larz60+
  Reading and appending list MrSwiss 1 1,720 Mar-01-2021, 09:01 AM
Last Post: Serafim
  Appending to list of list in For loop nico_mnbl 2 2,349 Sep-25-2020, 04:09 PM
Last Post: nico_mnbl
  Append list into list within a for loop rama27 2 2,356 Jul-21-2020, 04:49 AM
Last Post: deanhystad
  Need help with For Loop logic for reading docx Table column data vintysaw 2 3,872 Jan-10-2020, 06:36 AM
Last Post: vintysaw

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020