PyCodeItPython trace & SQL practice
python

13 Essential Python Trace Table Exercises

Thirteen Python trace table exercises with verified step-by-step walkthroughs covering mutable defaults, closures, decorators, and call stack behavior.

RD

By RichieDatalyst

Python & SQL learning guides-GitHub-PyCodeIt on LinkedIn

Published · Updated

8 min read

See the About page for curation and verification details.

This is a drill set, not a lecture. Thirteen short trace problems that cover the highest-frequency concepts in code tracing exercises: mutable defaults, late binding, generator state, comprehension scope, exception flow, aliasing, chained comparisons, dict mutation, decorators, recursion base cases, nonlocal scope, short-circuit evaluation, and extended starred unpacking. Every answer below was tested and verified on Python 3.12.10 (last verified: November 15, 2026). Work through them with paper and pencil first, check your trace table against the verified output, and note which category each miss falls into. Do one set a day for ten days and these stop being surprises.

Verification Note

Last verified: November 15, 2026 on Python 3.12.10. All code examples below were executed directly in a clean CPython environment with exact stdout captured.

1. Mutable default accumulator

def add(x, lst=[]):
    lst.append(x)
    return lst

print(add(1))
print(add(2))
Runtime Execution Output
Verified output:
[1]
[1, 2]

Both prints show the same growing list because the default list is created once at definition time and every call mutates that one object; the second call returns [1, 2], not a fresh [2]. The fix is the None sentinel: def add(x, lst=None): if lst is None: lst = []. Full walkthrough in the mutable-default-arguments article.

2. Late-binding lambdas in a loop

funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
fixed = [lambda i=i: i for i in range(3)]
print([f() for f in fixed])
Runtime Execution Output
Verified output:
[2, 2, 2]
[0, 1, 2]

The plain lambdas close over the variable i, not its value. By the time they are called, the loop finished and i is 2. The default-parameter trick i=i snapshots the value at definition time. This is the single most asked closure question.

3. Generator exhaustion

g = (x for x in range(2))
print(next(g), next(g))
try:
    next(g)
except StopIteration:
    print('StopIteration raised')
Runtime Execution Output
Verified output:
0 1
StopIteration raised

Generators are consumable, not re-iterable. Trace them with an explicit 'cursor position' note; a row like 'generator exhausted' prevents the classic wrong answer of printing 0 again.

4. Comprehension scope does not leak

x = 'outer'
res = [x for x in range(3)]
print(res, x)
Runtime Execution Output
Verified output:
[0, 1, 2] outer

In Python 3 comprehensions run in their own implicit function scope, so the loop variable x never touches the outer x. learners who learned Python 2 or copied old Stack Overflow answers predict 'outer' overwritten to 2. It is not.

5. Exception flow stops mid-block

x = 0
try:
    x = 1
    y = 1 / 0
    x = 2
except ZeroDivisionError:
    print('x after failed line:', x)
finally:
    print('finally ran')
Runtime Execution Output
Verified output:
x after failed line: 1
finally ran

The line that raised never completed, so x stayed 1 and y was never bound. Trace rules: when an exception fires, jump straight to the matching handler, skip the rest of the try block, and always run finally. Mark skipped rows in your table instead of silently omitting them.

6. Aliasing through assignment

a = [1, 2, 3]
b = a
b.append(4)
print(a)
Runtime Execution Output
Verified output:
[1, 2, 3, 4]

Assignment binds names; it does not copy objects. One list, two names. See the aliasing-and-shared-state article for the object-ID trace method that makes this automatic.

7. Chained comparisons

print(1 < 2 < 3) print(3 > 2 > 1) print(1 < 2 > 3)

Runtime Execution Output
Verified output:
True
True
False

Chains expand to and-ed pairs with the middle value evaluated once: 1 < 2 and 2 > 3 gives False. senior engineers ask variants like 1 < x < 5 with a traced x to see whether you split the chain correctly.

8. Dictionary mutation during iteration

d = {'a': 1, 'b': 5}
try:
    for k, v in d.items():
        if v < 3:
            del d[k]
except RuntimeError as e:
    print('RuntimeError:', e)
Runtime Execution Output
Verified output:
RuntimeError: dictionary changed size during iteration

Deleting bumps the dict's internal version counter and the live items view refuses to continue. Safe patterns: iterate list(d.keys()), or rebuild with a comprehension. Value updates without size changes are allowed.

9. Decorator wrapping order

def log(fn):
    def wrapper(*a):
        print('calling', fn.__name__)
        r = fn(*a)
        print('returned', r)
        return r
    return wrapper

@log
def double(x):
    return x * 2

double(5)
Runtime Execution Output
Verified output:
calling double
returned 10

@log replaced double with wrapper at definition time, so calling double(5) runs wrapper logic first. When tracing decorated functions, write two lanes: wrapper rows and inner-function rows. Most wrong predictions come from tracing only the visible function body.

10. Recursion base case discipline

def countdown(n):
    if n == 0:
        print('liftoff')
        return
    print(n)
    countdown(n - 1)

countdown(3)
Runtime Execution Output
Verified output:
3
2
1
liftoff

Change the base test to n <= 0 and countdown(0) still prints liftoff; change it to n < 0 and countdown(0) recurses forever until RecursionError. Always mark the exact base-case condition in your table before writing any frames.

11. Scope resolution with nonlocal versus global

def outer():
    count = 10
    def inner():
        nonlocal count
        count += 5
        return count
    return inner()

print(outer())
Runtime Execution Output
Verified output on Python 3.12.10:
15

Without nonlocal count, attempting to assign count += 5 inside inner raises UnboundLocalError: cannot access local variable 'count' where it is not associated with a value. Python sees assignment to count and marks it as local to inner, hiding the outer scope. Using nonlocal explicitly binds the assignment to the enclosing function's scope.

12. Short-circuit evaluation returning operands

Logical operators in Python (and / or) do not return booleans; they return the operand that determined the result:

a = [] or 'default'
b = [1, 2] and 'success'
print('a:', a)
print('b:', b)
Runtime Execution Output
Verified output:
a: default
b: success

Trace rule: X or Y evaluates X. If X is truthy, it returns X immediately without touching Y. If X is falsy, it evaluates and returns Y. For X and Y, if X is falsy it returns X immediately; if X is truthy it evaluates and returns Y. This behavior is standard for default value assignment in Python.

13. Extended iterable unpacking with starred expressions

head, *middle, tail = [10, 20, 30, 40, 50] print('head:', head) print('middle:', middle) print('tail:', tail)

Runtime Execution Output
Verified output:
head: 10
middle: [20, 30, 40]
tail: 50

Extended unpacking assigns the first element to head, the final element to tail, and packages all intermediate elements into a fresh list bound to middle. If the collection has fewer elements than required positional targets, Python raises ValueError at runtime.

Scoring yourself across 13 questions

11–13 correct (Advanced Mastery): Your code dry-running fundamentals are robust and you reason through runtime scope frames accurately. 8–10 correct (Solid Foundation): You have a strong baseline. Isolate the two or three categories where your predictions diverged (e.g. late binding or generator state) and review their worked walkthroughs. 0–7 correct (Needs Review): Focus on the fundamentals of object mutability, default parameters, and call stack unwinding before advancing to timed drills.

Comprehensive Synthesis & Execution Rubric

Tracing code accurately under timed manual code tracing conditions is a learned technical discipline. The thirteen questions above cover the specific runtime behaviors where learners most commonly lose composure: mutable default argument bindings, closure cell references, generator exhaustion states, exception block flow controls, and operator short-circuit boundaries.

When evaluating learners during live technical problem solving, engineering managers look for three distinct execution behaviors: 1. Deterministic state tracking: The developer systematically records variable values on paper or manual code tracing without relying on mental estimation or guesswork. 2. Articulated edge-case reasoning: The developer proactively notes boundary conditions (e.g. empty lists, negative strides, shared references) before the evaluator points them out. 3. Structured verbal narration: The developer connects the physical trace table directly to CPython execution mechanics, stating exactly which frame is active and which memory references are being mutated.

Diagnostic Scoring Matrix & Learning Path

Evaluate your final score against these clear diagnostic bands: - 11 to 13 Correct (Advanced Mastery): You possess a rigorous mental model of CPython execution mechanics. You understand pointer references, memory scopes, and generator state machines. Maintain readiness with periodic timed drills. - 8 to 10 Correct (Solid Foundation): You have good fundamental intuition but stumble on subtle boundary cases (such as default argument mutation or closure late-binding). Review the worked trace tables for questions you missed and step through the interactive practice topics. - 0 to 7 Correct (Needs Review): You are guessing output based on surface syntax rather than stepping through execution invariants. Do not memorize code patterns. Build the habit of drawing explicit trace tables on paper before answering.

Strategic Review Recommendations

To elevate your performance from foundational understanding to full mastery, focus your study on three deliberate practice habits: 1. Write out full memory diagrams for every recursive and generator function you practice. Do not mentally skim call stacks. 2. Identify the exact scope type (local, enclosing, global, builtin) for every variable binding. 3. Verify whether operators mutate collections in place (.append(), +=) or rebind references to new heap allocations (+). Consistently applying this verification methodology will eliminate execution surprises across any technical coding screen.

Practice all 13 execution patterns hands-on in our Python Code Tracing Practice Hub or test your foundational pointer mechanics in Variable Aliasing & Shared State.

Related Video

A curated companion video with short authored timestamps and a concise summary.

Short timestamps & notes

[00:00] Intro & problem list

[01:20] Worked example walkthroughs

[03:30] Common pitfalls and tips

Summary: Short practice problems and worked solutions for common trace-table exercises.

Related Python Tutorials