Python Internals & Exam Traps: Mutable Defaults, Slicing, Generators, LEGB & Hashing
Object binding model (is vs ==), mutable default argument trap, shallow vs deep copy, late-binding lambda closures, generators yield state machines, dict hash keys, and NumPy broadcasting rules.
1. The 4 Classic GATE DA Python Code-Trace Traps
Trap 1: Mutable Default Arguments Evaluated ONCE at def Time!
def append_item(val, bucket=[]):
bucket.append(val)
return bucket
print(append_item(1)) # [1]
print(append_item(2)) # [1, 2] <-- SAME list object reused across calls!
print(append_item(3, [])) # [3]
print(append_item(4)) # [1, 2, 4]
Trap 2: Row Aliasing in [[0] * 3] * 3 vs List Comprehension
grid = [[0] * 3] * 3 # 3 references to the EXACT SAME inner list!
grid[0][1] = 9
print(grid) # [[0, 9, 0], [0, 9, 0], [0, 9, 0]]
safe = [[0] * 3 for _ in range(3)] # 3 independent inner lists
Trap 3: Late-Binding Closures in Loops
funcs = [lambda x: x + i for i in range(4)]
print([f(10) for f in funcs]) # [13, 13, 13, 13] -- all look up final i = 3!
fixed = [lambda x, i=i: x + i for i in range(4)] # [10, 11, 12, 13]
Trap 4: What Can Be a dict Key or set Element?
Only hashable objects! int, float, str, bool, frozenset are hashable; a tuple is hashable ONLY IF every element inside it is recursively hashable ((1, (2, 3)) is valid; (1, [2, 3]) raises TypeError: unhashable type: 'list'!). Also note: True == 1 == 1.0 and hash(True) == hash(1) == 1, so {True: 'a', 1: 'b', 1.0: 'c'} has length ({True: 'c'})!
2. Generators (yield), LEGB Scope & NumPy Broadcasting
- LEGB Lookup Order: Local Enclosing (
nonlocal) Global (global) Built-in. - Generators (
yield): Lazily produce values one at a time in memory instead of materializing an list. - NumPy Broadcasting Rule (Right-Align Shapes): Dimensions are compatible when equal OR one of them is
1(e.g.,(4, 1) + (1, 3) -> (4, 3);(3, 2) + (3,)fails because right-aligned2 != 3!).
Practice Questions on This Chapter (3)
What are the values of -7 // 3 and -7 % 3 in Python 3 (compared to -2 and -1 in C/Java)?
What is printed by the Python code d = {True: "yes", 1: "one", 1.0: "float"}; print(len(d), d[True])?
What is the output of def f(x, a=[]): a.append(x); return len(a) when evaluated as print(f(10), f(20), f(30, []), f(40))?