-1

I tried two ways of building a matrix in Python. After building, they seems to be the same. But if I do one same operation on them, they become different. I don't understand what is going on. Look at the following code.

m = [[0]*3]*3
n = [[0]*3 for i in range(3)]

print("m is:")
print(m)

print("n is:")
print(n)

print("m equals n? {}".format(m == n))

m[0][0] = 1
n[0][0] = 1

print('after operation')

print("m is:")
print(m)

print("n is:")
print(n)

print("m equals n? {}".format(m == n))

The output is:

m is:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

n is:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

m equals n? True

after operation

m is:

[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

n is:

[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

m equals n? False
  • In list m, [1] and [2] point to the same location as [0], and will change as [0] changes. In list n, they are copies, that change seperate from each other. – Stef van der Zon Aug 22 '18 at 06:23
  • The expression, `seq * n` where `seq` is a sequence (like a `list`) and `n` is an `int` is equivalent to `seq + seq + ... seq` (n times). So, consider, `x = [[0,0,0]]`, then `m = x + x + x` and now it should be obvious why `m[0][0] = 42` will result in `[[42, 0, 0], [42, 0, 0], [42, 0, 0]]` – juanpa.arrivillaga Aug 22 '18 at 06:24

1 Answers1

1

m is 3 references to the same object, i.e. 3 references to[[0]*3], so if you change a part of the master, you see the change in all of the references...

In my machine I added these:

print(id(m[0]), id(m[1]), id(m[2]))
print(id(n[0]), id(n[1]), id(n[2]))

and the output is:

367335732232 367335732232 367335732232
367336105544 367338477832 367336105224

showing that m[0] is m[1] is m[2], unlike n[0], n[1], n[2]

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124