Stack

A stack provides Last-In, First-Out (LIFO) access; in Python, list.append and trailing list.pop() implement a stack in amortized O(1) time and allow converting recursive traversals into explicit loops.

One-Sentence Definition

A stack enforces Last-In, First-Out (LIFO) access; in Python, list.append() and trailing list.pop() implement a stack in amortized O(1)O(1) time, and an explicit stack can rewrite deep recursive traversals into iterative loops.

Why It Matters

  • Function calls run on a call stack: Every function call pushes a stack frame and every return pops it; the traceback printed on an uncaught exception is a snapshot of the call stack (see k1.prog.stack-trace).
  • Bracket matching, expression evaluation, Undo history, browser Back navigation, and Depth-First Search (see k2.algo.dfs) all rely on stacks.

Boundaries & Caveats

Python interpreter frame objects and the underlying OS C stack are distinct layers. Maximum recursion depth depends on the interpreter and runtime environment; raising the Python recursion limit too aggressively can increase memory consumption or overflow the underlying C stack.

How It Works / Diagram

Figure 1

In Python, a standard list using append() and trailing pop() provides amortized O(1)O(1) stack operations. Official Python tutorial section "Using Lists as Stacks": https://docs.python.org/3/tutorial/datastructures.html#using-lists-as-stacks

Runnable Example

Bracket matching, Reverse Polish Notation (RPN) evaluation, hitting the recursion limit, and rewriting deep recursion with an explicit heap-allocated stack (recorded run on Python 3.15.0):

# File: examples/10_stack.py
# Stack: Last-In, First-Out (LIFO). Implemented in Python via list.append() and list.pop()
def balanced(s: str) -> bool:
    pairs, stack = {")": "(", "]": "[", "}": "{"}, []
    for ch in s:
        if ch in "([{": stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]: return False
    return not stack
for s in ["{[()]}", "([)]", '{"a": [1, 2]}', "((" ]:
    print(f"{s!r:16} balanced: {balanced(s)}")

# Reverse Polish Notation (RPN) evaluation (classic calculator/compiler pattern)
def rpn(tokens):
    st = []
    for t in tokens:
        if t in "+-*/":
            b, a = st.pop(), st.pop()
            st.append({"+": a + b, "-": a - b, "*": a * b, "/": a / b}[t])
        else: st.append(float(t))
    return st[0]
print("(3 + 4) * 2 in RPN '3 4 + 2 *' =", rpn("3 4 + 2 *".split()))

# The function call stack is itself a stack: deep recursion raises RecursionError
import sys
def depth(n): return 0 if n == 0 else 1 + depth(n - 1)
print("Default recursion limit:", sys.getrecursionlimit())
try: depth(100_000)
except RecursionError as e: print("RecursionError:", e)

# Rewrite deep recursion into an iterative loop with an explicit stack (common in DFS)
def depth_iter(n):
    stack, d = [n], 0
    while stack:
        x = stack.pop()
        if x: d += 1; stack.append(x - 1)
    return d
print("Explicit stack handling 100,000 levels:", depth_iter(100_000))

Recorded output:

'{[()]}'         balanced: True
'([)]'           balanced: False
'{"a": [1, 2]}'  balanced: True
'(('             balanced: False
(3 + 4) * 2 in RPN '3 4 + 2 *' = 14.0
Default recursion limit: 1000
RecursionError: maximum recursion depth exceeded
Explicit stack handling 100,000 levels: 100000

The recursive version triggers RecursionError near Python's default recursion limit (~1,000 frames, depending on active call frames), whereas an explicit list-backed stack processes 100,000 levels cleanly. See sys.getrecursionlimit: https://docs.python.org/3/library/sys.html#sys.getrecursionlimit

Common Pitfalls

  • Calling pop(0) on a stack: Removing from index 0 pulls from the bottom of the list (FIFO queue behavior) and costs O(n)O(n) element shifts.
  • Popping from an empty stack: Raises IndexError: pop from empty list; always check if stack: first.
  • Blindly raising sys.setrecursionlimit: Setting a huge recursion limit can overflow the underlying OS C stack and crash the Python process; convert deep recursion to an explicit iterative stack instead.
  • Conflating the stack data structure with OS stack memory: One is an abstract LIFO container; the other is a thread's execution stack segment managed by the OS and runtime.

Connection to AI Development

  • Parsing structured LLM outputs: Validating balanced braces/brackets in streamed JSON or extracting nested code blocks relies directly on stack-based state machines.
  • Hierarchical agent task decomposition: Entering a subtask and returning to the parent task follows a LIFO stack discipline.

Further Reading

Comprehension Check

Does converting a recursive algorithm into an iterative loop with an explicit stack automatically reduce its space complexity to O(1)O(1)?

Reference answer: No. The explicit stack still stores pending states on the heap (taking O(d)O(d) space for depth dd); it simply avoids Python's call-frame recursion depth limit.

Verification & Reproduction

Verified on: 2026-10-14. Example status: Passed. Run log: 10_stack.py.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram