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
  • 35,739
  • 32
  • 114
  • 161
Alex Fung
  • 1,996
  • 13
  • 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
  • 9,310
  • 3
  • 28
  • 40
  • 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