Stacks and queues are collections with a strict rule about which item comes out next; a deque makes both fast.
Stack (LIFO)
- Stack: last in, first out. Add and remove at the same end (the top).
- push: add to the top. pop: remove and return the top. peek: read the top without removing.
- Build with a Python
list:appendto push,pop()(no arg) to pop,list[-1]to peek. - The “top” is the right end of the list.
appendandpop()are O(1); space is O(n).
Queue (FIFO)
- Queue: first in, first out. Enter at the back, leave from the front.
- enqueue: add to the back. dequeue: remove and return the front.
- A plain list is a poor queue:
pop(0)shifts all remaining items left, so it is O(n) per removal. - Use
dequefromcollections:appendto enqueue,popleftto dequeue, both O(1).
Deque (double-ended queue)
from collections import deque(not built in).- Four O(1) end moves:
append(right),appendleft(left),pop(right),popleft(left). - Reaching into the middle by index is O(n); use a
listif you need random access. - Works as a fast stack too, but a list already suffices for a stack.
Complexity
| Operation | list as stack | list as queue | deque |
|---|---|---|---|
add at back (append) | O(1) | O(1) | O(1) |
remove from back (pop()) | O(1) | — | O(1) |
add at front (appendleft) | — | — | O(1) |
remove from front (popleft/pop(0)) | — | O(n) | O(1) |
| peek top/front | O(1) | O(1) | O(1) |
| access middle | O(1) | O(1) | O(n) |
| space | O(n) | O(n) | O(n) |
Which end
STACK (LIFO) QUEUE (FIFO)
push/pop -> top enqueue -> back
newest leaves first oldest leaves first
front <- dequeue
Gotchas
pop()on an empty list /popleft()on an emptydequeraises an error. Checkif stack:before removing.- Using
list.pop(0)for a queue works but is O(n) per removal; usedeque+popleft. - Mixing up ends: a list-stack’s top is
list[-1], the right end. - Forgetting
from collections import dequeraisesNameError.
Uses
- Stack: undo history, the call stack, balanced brackets, expression evaluation.
- Queue: tasks in arrival order (print jobs, requests), breadth-first search (BFS).