βˆ‘GateAndNet
PlannerSign Up
INTERMEDIATEFrequently Tested 4 min read 3 views

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!

python
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

python
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

python
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 11 ({True: 'c'})!

2. Generators (yield), LEGB Scope & NumPy Broadcasting

  • LEGB Lookup Order: Local β†’\to Enclosing (nonlocal) β†’\to Global (global) β†’\to Built-in.
  • Generators (yield): Lazily produce values one at a time in O(1)\mathcal{O}(1) memory instead of materializing an O(n)\mathcal{O}(n) 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-aligned 2 != 3!).
Key Formulas Summary
Python Floor Division & Modulo Invariant (Sign Follows Divisor b!)
a=(a//b)β‹…b+(aβ€Šmodβ€Šb),e.g.Β βˆ’7//3=βˆ’3β€…β€ŠΒ andΒ β€…β€Šβˆ’7β€Šmodβ€Š3=+2a = (a \mathbin{//} b) \cdot b + (a \bmod b), \qquad \text{e.g. } -7 \mathbin{//} 3 = -3 \;\text{ and }\; -7 \bmod 3 = +2
Note: CRITICAL DIFFERENCE FROM C/JAVA: In C, -7 / 3 == -2 (truncates toward 0) and -7 % 3 == -1!
#Python#GATE DA#Mutable Default Trap#Generators#LEGB#Slicing#NumPy Broadcasting

Practice Questions on This Chapter (3)

Q1GATE DA 2024 PythonMCQEASY
+1M β€’ -0.33

What are the values of -7 // 3 and -7 % 3 in Python 3 (compared to -2 and -1 in C/Java)?

⚑ Click an option above to verify instantly
Q2GATE DA 2025 PythonMCQMEDIUM
+2M β€’ -0.67

What is printed by the Python code d = {True: "yes", 1: "one", 1.0: "float"}; print(len(d), d[True])?

⚑ Click an option above to verify instantly
Q3GATE DA PythonMCQMEDIUM
+2M β€’ -0.67

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))?

⚑ Click an option above to verify instantly
Next Topic SVD, Eckart-Young Low-Rank Approximation, PSD Matrices & KKT Convex Optimization