Python Course · Debugging lesson
Python Debugging Interview Questions: Find the Bug
Trace five Python failures involving aliases, defaults, iterators, exceptions and scope, with corrected code and tests.
Learn the pattern, trace runnable code, and test an edge case.
Core idea
Reduce the failure, inspect state, then protect the fix with a test.
Fix cause → retest
Change one case
The direct answer
Find the state change that makes the second step fail.
Python debugging interview questions often hide a state or control-flow assumption: two rows are the same object, a default list survives a call, an iterator is exhausted, an exception is swallowed, or a variable is local when you expected global. The fix begins with a minimal failing example.
This lesson contains five failure fixtures and corrected approaches. The official Python FAQ documents the mutable-default rule, while the unittest guide explains regression tests. The synced course pricing block follows this introduction.
Course access
Choose your next step in Python.
Review the current course options and access details here.
Heycademy Courses · Coming Soon
Master Python with Heycademy
We’re preparing an interactive learning experience with practical exercises, skill assessments and personalized learning to help you build confidence and master new skills.
We’re putting the finishing touches on this course. Please check back for updates.
A repeatable debugging routine
Reproduce before editing code.
Read the exception text or actual output first. Write an assertion that fails on the old code. Inspect object identity, variable binding or iterator position as relevant. Change only the line that addresses the cause. Then run the same assertion and a nearby normal case to check that the fix did not change the intended contract.
Worked grid alias
Multiplication repeats references, not nested objects.
grid = [[0] * 2] * 3
grid[0][0] = 9
assert grid == [[9, 0], [0, 0], [0, 0]] # failsThe outer list has three references to the same inner list. Changing one row appears in all three. The corrected construction allocates a new inner list for each iteration:
grid = [[0] * 2 for _ in range(3)]
grid[0][0] = 9
assert grid == [[9, 0], [0, 0], [0, 0]]Check identity if confused: in the broken form, grid[0] is grid[1] is true; in the repaired form it is false. This is a mutation and aliasing problem, not a numerical arithmetic problem.
Five failing fixtures
Predict failure, then open the repair.
| Case | Setup | Trigger | Expected by novice | Actual | Repair |
|---|---|---|---|---|---|
| Shared grid rows | grid = [[0] * 2] * 3 | grid[0][0] = 9 | [[9,0],[0,0],[0,0]] | All rows become [9,0]. | Use [[0] * 2 for _ in range(3)]. |
| Mutable default | A function defaults out to [] and appends x. | Call with 1; then call with 2. | [2] on second call | Second call returns [1,2]. | Use out=None and allocate inside. |
| Consumed iterator | it = iter([1,2]); list(it) | list(it) again | [1,2] again | Second list is empty. | Recreate iterator or materialize once. |
| Broad exception | try: int(“bad”) except Exception: return 0 | Invalid input | An explicit error or policy | Silent zero hides invalid data. | Catch ValueError narrowly and define policy. |
| Scope rebinding | A function increments count from outer scope without nonlocal. | Call the function. | Outer count becomes 1. | UnboundLocalError: count is local. | Pass state explicitly or use deliberate nonlocal/global design. |
The table gives a compact failure catalog. Reproduce each case in a scratch file before reading the repair. The first and second cases share mutable state, but their creation points differ. The iterator case is about one-pass consumption. The exception case is about hiding a failure. The scope case is about binding rules.
Keep building this skill
Turn the example into a tested solution.
Return to the course options whenever you are ready.
Default argument repair
A sentinel preserves an explicitly supplied empty list.
def collect(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
assert collect(1) == [1]
assert collect(2) == [2]
shared = []
assert collect(3, shared) is sharedThe last assertion matters: using if not bucket would replace an explicitly supplied empty list and break that contract. None distinguishes “caller omitted an argument” from “caller supplied an empty collection.” Python’s FAQ explains why the original default list is reused.
Iterator and exception repair
Preserve the actual input meaning.
A Python iterator advances as it is consumed. If two passes are required, either create a new iterator from a reusable source or materialize once, taking O(n) space. Do not call list(it) twice and assume both calls return the original values. If the source is an infinite stream, materializing is not viable; design for one pass.
For parsing, except Exception: return 0 turns malformed data into a valid-looking number. Catch the expected ValueError and choose a policy: raise a clearer exception, return a documented sentinel, or collect invalid rows for review. A coding interview answer should say which policy the function implements.
Fresh failure
Two names, one mutable object.
Predict the result: a = [[1], [2]]; b = a[:]; b[0].append(9). Is a[0] changed?
Show the reasoning
Yes. A slice creates a new outer list but copies references to the inner lists. a[0] and b[0] point to the same inner list, so both show [1,9]. A deep copy or explicit inner-copy policy is needed if independent nested data is required.
This new fixture tests whether you understand the aliasing principle beyond the grid-multiplication syntax.
Scope and iterator cases
Read the failure rather than guessing the fix.
For scope rebinding, count += 1 inside a function makes count local unless declared otherwise. Reading that local value before assignment causes UnboundLocalError. Passing count in and returning a new value often gives a simpler contract than modifying global state. A deliberate closure can use nonlocal, but it should be named and tested.
For an exhausted iterator, the second traversal does not magically restart. If a source list is available, create a fresh iterator. If only one iterator is available and the input is finite, materialize it once if memory allows. If the input may be infinite or too large, process in one pass. The right repair depends on resource and contract constraints, not just on making a test green.
Five executable repairs
Compare the broken function with the corrected one.
Each pair below is in the accompanying debug_examples.py file. Five regression tests deliberately verify the old failure and the repaired behavior. These are short, self-contained examples; they can be copied into a local Python 3.12 session.
Expected only first row to change; bad code changes every row.
Broken code
def make_grid_bad():
grid = [[0] * 2] * 3
grid[0][0] = 9
return gridCorrected code
def make_grid_good():
grid = [[0] * 2 for _ in range(3)]
grid[0][0] = 9
return gridRoot cause: The multiplication repeats one inner-list reference. The comprehension allocates separate rows.
Expected second call to return only its new item; bad code retains the first.
Broken code
def collect_bad(item, bucket=[]):
bucket.append(item)
return bucketCorrected code
def collect_good(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucketRoot cause: The default list was created once. The sentinel allocates only when argument is omitted.
Expected two identical passes; bad code returns an empty second pass.
Broken code
def two_passes_bad(values):
iterator = iter(values)
return list(iterator), list(iterator)Corrected code
def two_passes_good(values):
stored = list(values)
return stored[:], stored[:]Root cause: An iterator does not reset. The repaired version materializes a finite source once.
Expected invalid text to be surfaced; bad code reports a valid-looking zero.
Broken code
def parse_amount_bad(text):
try:
return int(text)
except Exception:
return 0Corrected code
def parse_amount_good(text):
try:
return int(text)
except ValueError as exc:
raise ValueError(f"Invalid amount: {text!r}") from excRoot cause: Catch the expected ValueError and raise a clearer error rather than hiding it.
Expected the outer count to increment; bad code raises UnboundLocalError.
Broken code
def bump_bad():
count += 1
return countCorrected code
def bump_good(count):
return count + 1Root cause: Pass state in and return a new value, avoiding hidden global mutation.
The repaired functions have different contracts where needed: parse_amount_good raises for invalid text, and bump_good returns new state instead of mutating a global. A debugger should make those decisions explicit rather than silently change output meaning.
FAQ
Questions about this skill.
Why does a list default retain values?
The default object is created at function definition and reused when the argument is omitted.
Why does the second list(it) return empty?
The iterator was already consumed.
Should I catch every exception?
Usually specify expected failures and a clear error policy; broad catches can hide bugs.
Continue with the course
Build reliable Python interview skills.
Review the course options and choose your next learning step.