⚡ Boss Chapter

Python Gotchas
Greatest Hits

The ultimate collection. Cross-chapter surprises, interview traps, and the questions that make experienced Python developers pause. Good luck.

Questions: 20
Difficulty: ★★★★★
Final boss rules: These are the questions most likely to appear in Python interviews and the ones that cause the most production bugs. Take your time with each one. Every wrong answer is a lesson.
Classic Gotchas
Q 01Predict the Output
def f(x=[]):
    x.append(1)
    return x

print(f())
print(f())
print(f([]))
Output
[1] [1, 1] [1]
Why? The mutable default argument trap again — the definitive Python gotcha. The default [] is shared across calls. First call: appends 1 → [1]. Second call: same list, appends 1 → [1,1]. Third call: explicit empty list is passed — fresh start → [1].
Q 02Predict the Output
funcs = [lambda i=i: i for i in range(3)]
print(funcs[0]())
print(funcs[1]())
print(funcs[2]())
Output
0 1 2
Why? This is the FIXED version of the late-binding closure trap. lambda i=i: i captures the current value of i as a default argument at creation time. Each lambda gets its own copy of the value. Compare with lambda: i which would give 2, 2, 2.
Q 03Predict the Output
x = 256
y = 256
print(x is y)

x = 257
y = 257
print(x is y)
Output
True False
Why? CPython caches integers -5 to 256 as singletons. 256 is in the cache → same object. 257 is above the cache → different objects. This is a CPython implementation detail, not guaranteed by the language spec. Never use is to compare integers.
Q 04Predict the Output
class A:
    items = []

a = A()
b = A()
a.items.append(1)
print(b.items)
Output
[1]
Why? Mutable class attribute trap. items is a class attribute — shared by ALL instances. Mutating it through a is visible through b (and through A.items). Fix: move to __init__ with self.items = [].
Q 05Multiple Choice
a = [1]
b = a
a = a + [2]   # creates new list
print(b)
Answer: a) [1].

a + [2] creates a new list. a is rebound to this new list. b still points to the original [1]. If it were a += [2], the list would be mutated in-place and b would show [1, 2]. This is the crucial a = a + x vs a += x distinction.
Type Surprises
Q 06Predict the Output
print(type(True).__name__)
print(True + True + True)
print([False, True, True, False].count(True))
print(sum([True, False, True]))
Output
bool 3 2 2
Why? bool is a subclass of int. True==1, False==0. True + True + True = 3. .count(True) counts items equal to True — but also counts 1 (since True==1)! sum([True,False,True]) is 1+0+1=2. Counting booleans in a list with sum() is idiomatic Python.
Q 07Predict the Output
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(round(0.5))
print(round(1.5))
Output
0.30000000000000004 False 0 2
Why? Two classics in one. Float imprecision: 0.1+0.2 is not exactly 0.3 in binary IEEE 754. Banker's rounding: round(0.5) → 0 (rounds to even), round(1.5) → 2 (rounds to even). Python's rounding behavior shocks people coming from other languages.
Q 08Multiple Choice
print(not "")
print(not 0)
print(not [])
print(not {})
print(not None)
Answer: a) All True.

All these are falsy values: empty string, 0, empty list, empty dict, None. not falsy is always True. Truthiness rules: empty containers are falsy, zero values are falsy, None is falsy. Everything else is truthy.
Scope & Closure Traps
Q 09Predict the Output
x = 10

def f():
    x += 1   # attempts to modify x
    return x

try:
    print(f())
except UnboundLocalError as e:
    print("UnboundLocalError")
Output
UnboundLocalError
Why? Since x += 1 is an assignment to x, Python marks x as local to f(). Then x += 1 tries to read x (to add 1) before it's assigned → UnboundLocalError. To modify the global: add global x at the top of f().
Q 10Predict the Output
def make_multiplier(n):
    return lambda x: x * n

double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5))
print(triple(5))
Output
10 15
Why? Each call to make_multiplier creates a closure that captures its own n. double closes over n=2, triple closes over n=3. These are different closure objects with different captured values. This works correctly because each function call creates its own scope.
Container Traps
Q 11Predict the Output
d = {True: "T", 1: "one", 1.0: "1.0"}
print(d)
print(len(d))
Output
{True: '1.0'} 1
Why? True, 1, and 1.0 are all equal AND have the same hash. So they are the SAME dict key. Python keeps the FIRST key (True) but overwrites the value with each subsequent assignment. Final value is "1.0" (last one wins). One key, final value from last update.
Q 12Predict the Output
t = (1, 2)
t2 = t
t += (3,)
print(t)
print(t2)
print(t is t2)
Output
(1, 2, 3) (1, 2) False
Why? Tuples are immutable. t += (3,) creates a NEW tuple and rebinds t. t2 still points to the original (1,2). After the operation, t is t2 is False — different objects. This contrasts with lists where += mutates in-place.
Q 13Multiple Choice
a = [1, 2, 3]
b = a
a += [4]   # in-place extend
print(b)
Answer: b) [1, 2, 3, 4].

For lists, += calls __iadd__ which mutates in-place. Both a and b point to the same list object. After a += [4], the shared list is extended. b sees the change. This is the opposite of the tuple case (Q12) — lists mutate, tuples rebind.
Iteration Surprises
Q 14Predict the Output
a = [1, 2, 3]
b = [4, 5]
c = [6]
print(list(zip(a, b, c)))
Output
[(1, 4, 6)]
Why? zip() stops at the shortest iterable. With lengths 3, 2, 1 — only 1 tuple is produced. Elements 2 and 3 from a and element 5 from b are dropped. This is a common source of silent bugs when zipping lists of different lengths.
Q 15Multiple Choice
gen = (x for x in range(10))
print(list(gen))
print(sum(gen))
Answer: b) [0..9], 0.

After list(gen) exhausts the generator, sum(gen) sums over an already-exhausted generator, giving 0. No error — just empty. Generator exhaustion is the most common iterator trap. Always recreate a generator if you need to iterate it again.
String & Comparison Traps
Q 16Predict the Output
print("abc" is "abc")      # literal interning
x = "abc"
y = "abc"
print(x is y)                 # variable interning
z = "a" + "bc"
print(z is "abc")            # may vary
Output (CPython typical)
True True True
Why? CPython interns string literals that look like identifiers. Compile-time constant folding also makes "a" + "bc" become "abc" at compile time — interned. The results depend heavily on the Python implementation and version. The lesson: NEVER rely on string identity. Always use ==.
Q 17Predict the Output
print(1 < 2 == 2 < 3)
print(True == 1 == 1.0)
print(False == 0 == 0.0)
Output
True True True
Why? Python chained comparisons. 1 < 2 == 2 < 3: (1<2) and (2==2) and (2<3) → all True. True==1==1.0: (True==1) and (1==1.0) → True and True. Chained comparisons check each consecutive pair.
Tricky Operators
Q 18Predict the Output
print(-1 % 10)
print(int(-3.9))
print(-3 // 2)
print(-3 % 2)
Output
9 -3 -2 1
Why? Python's modulo/floor-division follow mathematical floor toward -∞. -1 % 10 = 9 (not -1 like C). int(-3.9) = -3 (truncates toward 0). -3 // 2 = -2 (floors toward -∞, not -1). -3 % 2 = 1 (sign matches divisor 2). All different from C behavior.
Q 19Multiple Choice
def f(x, y=None):
    if y is None:
        y = []
    y.append(x)
    return y

print(f(1))
print(f(2))
print(f(3, [10]))
Answer: a) [1], [2], [10, 3].

This is the CORRECT pattern for mutable default arguments. Using None as default and creating a fresh list inside the function means each call without explicit y gets its own independent list. Calls are independent: [1], then [2] (fresh list), then [10] with 3 appended.
Q 20Boss Question
x = [1, 2, 3]

class A:
    items = x     # class attr points to x

x.append(4)       # mutate x after class definition
print(A.items)
Output
[1, 2, 3, 4]
Why? A.items = x stores a reference to the list object x points to. Appending to x mutates the shared list object. A.items and x are the same object — any mutation is visible through both names. Class definition doesn't copy the value — it stores the reference. This is the ultimate test of reference semantics.

You Finished! 🎉

You've made it through all 13 chapters and 226 questions of Python Under the Hood. If you got most right, you're well prepared for Python interviews and production code. Review any chapters where you struggled.

← Back to Table of Contents
← Chapter 12: Exceptions Chapter 14: Tensor Fundamentals →