1

When running the following Python code:

mat1=[[0]*3]*3
mat2=[[0 for i in range(3)] for j in range(3)]

if(mat1==mat2):
    print("Same content")

mat1[1][1]=7
mat2[1][1]=7

print(mat1)
print(mat2)

I get this result:

Same content
[[0, 7, 0], [0, 7, 0], [0, 7, 0]]
[[0, 0, 0], [0, 7, 0], [0, 0, 0]]

Why is there a difference in the result, and what's wrong with my first way of initializing a matrix?

Ohad
  • 143
  • 5
  • 2
    Short answer, because `mat1=[[0]*3]*3` creates a *list of lists* where the sublists *are all the same list*. That is how the `*` works in Python. So, `[x]*3` is equivalent to `[x, x, x]`. Note, this is consistent with the `+` concatenation operator on lists, i.e. `a_list + a_list + a_list` is equivalent to `a_list * 3` – juanpa.arrivillaga Aug 31 '17 at 18:43

0 Answers0