Matching brackets
In ([]{}) every closing bracket must match the most recent bracket still open. Most recent first is last in, first out: the rule of a stack. A Python list works as one: append() pushes on top, pop() takes the top off.
Read the input left to right. ( is an opener, so line 6 pushes it. [ is an opener too, so it lands on top of (. The stack holds exactly the brackets still waiting for a partner.
] is a closer. Line 8 pops the top item and checks that it is the matching opener. The top is [, so the pair is good and both are done. ( still waits underneath.
{ is pushed on top of (. Then } pops it: a match. A closer only ever looks at the top of the stack, never deeper, so each character costs one push or one pop.
) pops (, the last opener. The loop ends and line 10 returns not stack: an empty stack means every opener found its partner, so the answer is True. The work grows in step with the length: O(n).
In (] the closer ] pops (, the wrong partner, so line 9 returns False. A string like (( fails the other way: the loop ends with ( still on the stack, so not stack is False.
Undo
A text editor uses the same idea. Each time you type, it pushes a note of that edit onto an undo stack. Type c, a, t and the stack holds +c, +a, +t, newest on top.
Press undo and the editor pops the top edit, +t, and reverses it: the text goes from cat back to ca. Press it again and +a comes off next. Undo always takes back the newest change first.
Evaluating expressions
In postfix the operator comes after its two numbers: 3 4 + 2 * means (3 + 4) × 2. Numbers are pushed. + pops 4, then 3, adds them and pushes 7.
2 is pushed on top of 7. * pops 2, then 7, multiplies and pushes 14. At the end one number is left on the stack: the answer, 14. No brackets or precedence rules were needed.
What happens
;; step 1/10 · why-stack
input: "([]{})"
rule: a closer must match the newest opener still open
stack = [] # a Python list
stack.append(x) # push x on top
stack.pop() # remove and return the top
The not stack test on line 8 matters: a closer with nothing open, as in ")(", would make pop() on an empty list raise IndexError. Python checks not stack first and stops there, so pop() never runs on an empty list. Python list append() and pop() from the end take amortized O(1) time (MIT 6.006, lecture 2), so balanced() and eval_postfix() run in O(n) time for n characters or tokens. In the worst case, such as "((((", the stack grows to n items.