1stack = [] # a plain list is all you need2 3stack.append(9) # push — 9 goes on top4stack.append(4) # push — 4 is the new top5stack[-1] # peek — read the top (4), leave it6stack.pop() # pop — remove & return the top (4)7len(stack) # -> 1 · every line here is O(1)1from collections import deque2 3q = deque([5, 2, 8]) # front is 5, back is 84q.append(4) # enqueue — 4 joins the back5q.popleft() # dequeue — 5 leaves the front (-> 5)6q[0] # peek — the front is now 27len(q) # -> 3 · append & popleft are O(1)Stack = a plain list
The end of the list is the top. Adding and removing there never disturb the other items, so both stay fast.
stack.append(x)O(1)stack.pop()O(1)Queue ≠ a plain list
Removing from the front of a list re-indexes every item behind it. Reach for collections.deque, built to be fast at both ends.
list.pop(0)O(n)deque.popleft()O(1)Undo / redo
Every action you take is pushed onto a stack. Undo pops the most recent one back off.
The browser Back button
Each page you visit is pushed; Back pops you to the page right before it.
The call stack
Function calls stack up and unwind in reverse — the exact stack recursion runs on.
Matching brackets
Push each opening bracket, pop on every closing one. Empty at the end means the brackets balance.
Print jobs
Documents print in the order you sent them — first in, first out.
Message & task queues
Work is added at the back and handled from the front, strictly in arrival order.
Breadth-first search
Exploring a tree or graph level by level keeps a queue of the nodes still to visit.
Customer service lines
Whoever called first is answered first — the everyday queue you already know.
| Structure | Add | Remove | Python | Cost |
|---|---|---|---|---|
| Stack (LIFO) | push append() | pop pop() | list | O(1) |
| Queue (FIFO) | enqueue append() | dequeue popleft() | collections.deque | O(1) |