ALGORITHMSChapter 10 · Algorithms and Problem Solving
Stacks and queues
A stack is last in, first out, like a pile of plates: push with .append() and pop with .pop(). A queue is first in, first out, like a line of people: use collections.deque, add with .append() and remove from the front with .popleft(), which is fast (unlike list.pop(0)). Stacks power undo and bracket matching; queues schedule work in order.
Worked example
How it reads
stack.pop()takes the most recent item: the last thing done is the first undonequeue.popleft()takes the oldest item: first come, first serveddequeadds and removes at both ends in O(1)

Cloud tip: Whenever something must be matched in reverse order (brackets, tags, undo), think stack.


