Predict the output · Python
List Multiplication Shares Rows
Easy Predict the output Seen at Amazon, Meta
What does this print?
What does this print?
grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid)
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
[[1, 1, 1], [0, 0, 0], [0, 0, 0]]
TypeError
Check your answer
Loading the editor… (JavaScript is required to run code in your browser.)
Solution
Show the answer
The output is:
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
* 3 on the outer list copies the reference to the inner list three times, so all rows are the same object. Build independent rows with a comprehension: [[0] * 3 for _ in range(3)]. (Multiplying the inner [0] is fine because integers are immutable.)
More Gotchas problems
- var in a Loop with setTimeout · Easy
- Microtasks vs Macrotasks · Medium
- Type Coercion Surprises · Medium
- Numeric Enums at Runtime · Medium
- Type Assertions Don't Convert · Easy
- readonly and as const at Runtime · Medium