0

When I want to update one element(1,1) of the matrix, both (0,1) and (1,1) are updated, why it is like this?

In [188]: matrix_res = [[0]*2]*2

In [189]: matrix_res

Out[189]: [[0, 0], [0, 0]]

In [190]: matrix_res[1][1] = 1

In [191]: matrix_res

Out[191]: [[0, 1], [0, 1]]
Bach
  • 6,145
  • 7
  • 36
  • 61

3 Answers3

0

It is because the [0]*2 is created once. Then the outer *2 uses the same object to make a outer array (by making 2 references to the same [0]*2).

So that when you modify any one, the other one will also be modified. In fact, they are the same object.

HKTonyLee
  • 3,111
  • 23
  • 34
0

Replace this line:

matrix_res = [[0]*2]*2

with this:

matrix_res = [[0 for i in range(2)] for j in range(2)]

or simply:

matrix_res = [[0, 0], [0, 0]]

Reason: in matrix_res = [[0]*2]*2 there's actually only one inner list created and the two sublist in matrix_res are all tagged to that only one.

starrify
  • 14,307
  • 5
  • 33
  • 50
0

Thanks all guys. You are all correct. Below is the information I took from Python documentation for those who want to see more details:

=========================================================

Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s). Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers; consider:

>>>

>>> lists = [[ ]] * 3

>>> lists [[ ], [ ], [ ]]

>>> lists[0].append(3)

>>> lists [[3], [3], [3]]

What has happened is that [[ ]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are (pointers to) this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:

>>>

>>> lists = [[] for i in range(3)]

>>> lists[0].append(3)

>>> lists[1].append(5)

>>> lists[2].append(7)

>>> lists

[[3], [5], [7]]

  • "those who want to see more details" are advised to look at the documentation rather than here. (Since this is not an authoritative source and it's likely to become outdated sooner or later.) With all respect I don't see much value in this answer – Alois Mahdal Feb 24 '14 at 18:38