# Python Internals & Exam Traps: Mutable Defaults, Slicing, Generators, LEGB & Hashing
Exam: GATE Data Science & Artificial Intelligence (DA) (GATE DA)
Subject: Python Programming, Data Structures & Algorithms
Canonical URL: https://gateandnet.com/exams/gate-da/python-programming-dsa/python-mutable-defaults-slicing-generators-and-legb

> 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 **$1$** (`{True: 'c'}`)!

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

- **LEGB Lookup Order:** **L**ocal $\to$ **E**nclosing (`nonlocal`) $\to$ **G**lobal (`global`) $\to$ **B**uilt-in.
- **Generators (`yield`):** Lazily produce values one at a time in $\mathcal{O}(1)$ memory instead of materializing an $\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`!).

## Solved Practice Questions & PYQs

### [GATE DA 2024 Python | MCQ]
What are the values of `-7 // 3` and `-7 % 3` in **Python 3** (compared to `-2` and `-1` in C/Java)?
**Correct Answer:** B
**Solution:** Python `//` floors toward **$-\infty$**: $\lfloor -2.333 \rfloor = \mathbf{-3}$. Since $(-3)(3) + r = -7$, remainder $r = \mathbf{+2}$ (always matching the sign of the positive divisor `3`!).

### [GATE DA 2025 Python | MCQ]
What is printed by the Python code `d = {True: "yes", 1: "one", 1.0: "float"}; print(len(d), d[True])`?
**Correct Answer:** B
**Solution:** In Python, `True == 1 == 1.0` and `hash(True) == hash(1) == hash(1.0) == 1`! Keys keep the **first inserted key object** (`True`) while overwriting its **value** sequentially (`"yes" -> "one" -> "float"`), so `len(d) == 1` and `d[True] == "float"`!

### [GATE DA Python | MCQ]
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))`?
**Correct Answer:** B
**Solution:** Default list `a=[]` is created **once** at function definition:
1. `f(10)` $\to [10]$ (len `1`)
2. `f(20)` $\to [10, 20]$ (len `2`)
3. `f(30, [])` uses a temporary fresh list $\to [30]$ (len `1`)
4. `f(40)` reuses the persistent default list $\to [10, 20, 40]$ (len **`3`**)!
