0

Is there any reason why the below happens? In both cases, we defined grid as 3 by 3 array of zeroes, but when we change middle value to 2, three values are changed to 2 whereas in the second case, only one value was changed to 2.

grid=[[0]*3]*3
grid[1][1]=2
print(grid)
[[0, 2, 0], [0, 2, 0], [0, 2, 0]]

grid=[[0 for i in range(3)] for i in range(3)] 
grid[1][1]=2
print(grid)
[[0, 0, 0], [0, 2, 0], [0, 0, 0]]
user98235
  • 830
  • 1
  • 13
  • 31
  • Related: https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it – Thomas Weller Mar 04 '22 at 12:04

1 Answers1

0

With the grid=[[0]*3]*3 method, all arrays in grid hold the same memory address. So if you change any of them, the same output is shown for all of them.

You'll notice that all three of these have the same value:

id(grid[0])
id(grid[1])
id(grid[2])
mike.k
  • 3,277
  • 1
  • 12
  • 18