MiddleCodeOccasionalNot answered yet
What does [[0]*3]*3 print after a write?
Predict the grid after the assignment.
grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid)
Determine the output and explain.
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]. The outer * 3 copies the reference to the same inner list three times, so mutating one row mutates all. Fix with a comprehension that builds independent rows: grid = [[0] * 3 for _ in range(3)].
- ✗Believing
* 3deep-copies the inner list - ✗Confusing list multiplication with NumPy broadcasting
- ✗Not knowing the comprehension fix for independent rows
- →Why does
[[0] * 3 for _ in range(3)]build independent rows? - →Does the same aliasing trap apply to
[0] * 3of immutable ints?