1
matrix = [[0]*1005]*1005

and

matrix = [[0 for _ in range(1005)] for _ in range(1005)]

I found if i using the former to initial array, and run matrix[1][1] = 1 it will set the second column in every row to 1. And the second performed as i wished. I can't figure out why?

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
Frank Cheng
  • 5,928
  • 9
  • 52
  • 80
  • possible duplicate of ["Least Astonishment" in Python: The Mutable Default Argument](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument) – Joel Cornett Jul 05 '12 at 00:31
  • Oops. That wasn't the question I wanted to select. – Joel Cornett Jul 05 '12 at 00:32

2 Answers2

8

[[0] * 1005] * 1005 will create an array of 1005 references to an array with 1005 zeroes. They're all the same reference, and so changing one will change all the others. You can shorten your working code to this, though:

matrix = [[0] * 1005 for _ in range(1005)]

This is pretty much the only warning anybody ever gives you about the list multiplication syntax, actually :)

Ry-
  • 218,210
  • 55
  • 464
  • 476
3

Just to expand on whats already been said

a = [[0]] * 5
print a # [[0], [0], [0], [0], [0]]
a[0][0] = 1
print a # [[1], [1], [1], [1], [1]]
Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91