Python Stacks and Queues With Lists
A stack takes items off in reverse order. A queue takes items off in arrival order. A plain list can act as either one.
A stack undoes in reverse
The last line pushed is the first line popped. Two pops leave only "a" behind.
stack = []
stack.append("a")
stack.append("b")
stack.append("c")
print(stack.pop())
print(stack.pop())
print(stack)A queue serves in arrival order
Ada joined first, so Ada leaves first. Cy still waits at the end.
queue = []
queue.append("ada")
queue.append("bob")
queue.append("cy")
print(queue.pop(0))
print(queue.pop(0))
print(queue)pop() and pop(0) differ
pop() takes "last" from the end. pop(0) then takes "first" from the front.
items = ["first", "middle", "last"]
print(items.pop())
print(items)
print(items.pop(0))
print(items)Example
undo = []
undo.append("write line 1")
undo.append("write line 2")
undo.append("write line 3")
print("Undo:", undo.pop())
print("Left:", undo)
queue = []
queue.append("ada")
queue.append("bob")
queue.append("cy")
print("Serve:", queue.pop(0))
print("Serve:", queue.pop(0))
print("Waiting:", queue)Key points
- Stack: items taken off in reverse order, last in first out
- Use append() to push an item onto a stack
- Use pop() to take the top item off a stack
- Queue: items taken off in arrival order, first in first out
- Use append() to join the back of a queue
- Use pop(0) to take the front item off a queue
- pop() takes the last item, while pop(0) takes the first item
In this example, the undo stack holds three written lines. pop() takes back line 3 first, and two lines stay behind. The queue holds three waiting names. pop(0) serves Ada first, then Bob, and Cy still waits. The two orders prove the stack and the queue pull from opposite ends.
Note
pop(0) costs more on a long list, since every item behind the front shifts one place.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which call takes the front item off a queue?