10 Tricky Python Output Prediction Questions & Tricks
Output prediction questions are a staple of Python job interviews at top tech companies. They test whether you truly understand Python's internal memory model, evaluation rules, scope mechanics, and object mutability rather than just remembering basic syntax.
Below are 10 classic output prediction traps along with step-by-step mental simulation guides.
1. The Mutable Default Argument Trap
def append_to(element, target=[]):
target.append(element)
return target
print(append_to(1))
print(append_to(2))
print(append_to(3, []))
print(append_to(4))
Predicted Output:
[1]
[1, 2]
[3]
[1, 2, 4]
Why: Python creates default argument objects once at function definition time. Calls 1, 2, and 4 reuse the exact same default list object in memory! Call 3 explicitly passes a new list [], leaving the default list untouched.
2. Short-Circuit Logical Operator Evaluation
x = 0 or "Python"
y = [] and "Code"
z = "Hello" or "World"
print(x, "|", y, "|", z)
Predicted Output:
Python | [] | Hello
Why: In Python, or returns the first truthy value it meets (or the last value if all are falsy). and returns the first falsy value (or the last value if all are truthy). They do not return boolean True/False unless the operands themselves are booleans.
3. Late Binding in Closures & Comprehensions
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])
Predicted Output:
[2, 2, 2]
Why: Python closures look up variable i when the function is called, not when it is defined. By the time f() is called, the loop has completed and i = 2.
4. Is vs == (Identity vs Equality) with Small Integers
a = 256
b = 256
print(a is b)
c = 257
d = 257
print(c is d)
Predicted Output:
True
False (or True in interactive REPL / optimizations)
Why: Python caches integer objects in the range -5 to 256 (Small Integer Caching). 256 shares memory address (is returns True), whereas 257 usually allocates separate objects.
5. List Multiplication Aliasing Trap
matrix = [[0] * 2] * 2
matrix[0][0] = 99
print(matrix)
Predicted Output:
[[99, 0], [99, 0]]
Why: [[0] * 2] * 2 duplicates references to the same sublist rather than copying it! Updating index 0 updates all rows because they point to the identical list object in memory.
🧠 Practice Output Prediction Live
Solve 30+ interactive output prediction questions on PyDebug right in your browser!
Try Output Prediction Quiz →Summary & Key Takeaways
- Always check whether objects are mutable or immutable.
- Remember that default function arguments are evaluated once at definition time.
- Trace logical short-circuiting step-by-step.
- Use PyDebug Playground to experiment with tricky snippets.