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. [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
  2. [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
  3. [[1, 1, 1], [0, 0, 0], [0, 0, 0]]
  4. 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.)