The ultimate collection. Cross-chapter surprises, interview traps, and the questions that make experienced Python developers pause. Good luck.
def f(x=[]): x.append(1) return x print(f()) print(f()) print(f([]))
[] 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].funcs = [lambda i=i: i for i in range(3)] print(funcs[0]()) print(funcs[1]()) print(funcs[2]())
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.x = 256 y = 256 print(x is y) x = 257 y = 257 print(x is y)
is to compare integers.class A: items = [] a = A() b = A() a.items.append(1) print(b.items)
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 = [].a = [1] b = a a = a + [2] # creates new list print(b)
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.print(type(True).__name__) print(True + True + True) print([False, True, True, False].count(True)) print(sum([True, False, True]))
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.print(0.1 + 0.2) print(0.1 + 0.2 == 0.3) print(round(0.5)) print(round(1.5))
print(not "") print(not 0) print(not []) print(not {}) print(not None)
not falsy is always True. Truthiness rules: empty containers are falsy, zero values are falsy, None is falsy. Everything else is truthy.x = 10 def f(): x += 1 # attempts to modify x return x try: print(f()) except UnboundLocalError as e: print("UnboundLocalError")
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().def make_multiplier(n): return lambda x: x * n double = make_multiplier(2) triple = make_multiplier(3) print(double(5)) print(triple(5))
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.d = {True: "T", 1: "one", 1.0: "1.0"}
print(d)
print(len(d))
t = (1, 2) t2 = t t += (3,) print(t) print(t2) print(t is t2)
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.a = [1, 2, 3] b = a a += [4] # in-place extend print(b)
+= 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.a = [1, 2, 3] b = [4, 5] c = [6] print(list(zip(a, b, c)))
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.gen = (x for x in range(10)) print(list(gen)) print(sum(gen))
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.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
"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 ==.print(1 < 2 == 2 < 3) print(True == 1 == 1.0) print(False == 0 == 0.0)
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.print(-1 % 10) print(int(-3.9)) print(-3 // 2) print(-3 % 2)
-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.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]))
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.x = [1, 2, 3] class A: items = x # class attr points to x x.append(4) # mutate x after class definition print(A.items)
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'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