0
n=7
m=[[0]*n]*n
for i in range(n):
  m[i][i]=1
print(m)

Output:[[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1]]

BUT

n=7
m = [[0 for x in range(n)] for x in range(n)] 
for i in range(n):
  m[i][i]=1
print(m)

Output:[[1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1]]

why are the output different?

  • 2
    In the first case all the sub lists are the same object. In the second case they are different objects with the same (initial) value. – alani Jul 17 '20 at 03:18
  • Look at `set(id(x) for x in m)` and you will see the difference clearly. – alani Jul 17 '20 at 03:20
  • In the first case, try `m[0][i]=1` instead of `m[i][i]=1`. The result is the same because all the `m[i]` are the same object. – alani Jul 17 '20 at 03:26

0 Answers0