Python problem 17 of 30

The copied grid

  • Python
  • Medium

What does this print, and why? Fix it so only one cell changes.

grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid)
Show hint

* 3 on a list copies references, not the objects they point to.

Show solution
# Prints:
# [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

grid = [[0] * 3 for _ in range(3)]
grid[0][0] = 1
# [[1, 0, 0], [0, 0, 0], [0, 0, 0]]

The outer * 3 makes three references to the same inner list, so changing it through any row changes "all" of them. The list comprehension creates a new inner list on each pass. [0] * 3 itself is fine because integers are immutable.

Want a problem like this every day? See today's problem and keep a streak going.