In Python 2.7.11, I am creating a two-dimensional list in this way:
array1 = [[0]*2]*2
array2 = [[0 for i in range(2)] for j in range(2)]
Both of them give me [[0,0], [0,0]]
, but when it comes to modification, they yield different answers:
array1[0][0] = 1
array2[0][0] = 1
Now array1 = [[1,0], [1,0]]
, array2 = [[1,0], [0,0]]
. Apparently array2 is what I expected, but any idea on why array1 behaves differently? I am assuming that array1 is copying the first row to create the matrix and therefore any modification to one of the rows will also affect other rows. But I have been using [None]*size to initialize a one dimensional list and it works fine all the time.