1

I noticed a weird behavior when I am changing a value in a nested list grid which is initialized as such grid = [[0]*10]*10.

grid = [[0]*10]*10

grid[0][0] = 1

for l in grid:
    print l

Output:

[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]

When I initialised grid as grid = [[0]*10 for x in range(10)]. It worked as expected.

grid = [[0]*10 for x in range(10)]

grid[0][0] = 1

for l in grid:
    print l

Output:

[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Does anyone know why this happened?

Thank you for your help!

Wasi Ahmad
  • 31,685
  • 30
  • 101
  • 155
Alex Fung
  • 1,966
  • 11
  • 21

1 Answers1

2

When you create grid = [[0]*10]*10, you are actually creating an array of references to the same object (a list of [0]s). So when you change the object via one reference, this changes all entries in the list.

This is a very common Python 'gotcha' for beginners.

Andrew Guy
  • 8,390
  • 3
  • 26
  • 38
  • yes @Andrew is correct. # Explanation grid = [[0]*10]*10 # here initiated a list and assigned to grid grid = [[0]*10 for x in range(10)] # here constructing a list and assigning to grid – Amitkumar Karnik Feb 13 '17 at 09:50