0

I have just got a question from a collegue, but I couldn't exlpain it well to him.
the problem is that the result of two operation was different.
example code is like this

n,m = 10,10 d = [[0]* m for _ in range(n)] f = [[ 0 ] * m] * n

and the situation that I'm in a pickle is as follows.

d[0][1] = 1-> it sets only [0][1] to 1

f[0][1] = 1-> it sets all the elements in the column of index to 1

the results

d = [[0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
f = [[0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0]]

I tried bool(d==f), but the result was True.
I'm so confused of this difference.
please help me, please let me know why it is!
thank you for reading my question.

김범석
  • 55
  • 6
  • `[[0]* m for _ in range(n)]` this creates *n* lists of size *m* filled with zeros, `[[ 0 ] * m] * n` this creates a *n* references to the object `[ 0 ] * m]` so any change in one them is reflected in everyone of them. – Ch3steR May 23 '20 at 05:40
  • @Ch3steR thank you for letting me know! I've resolved it with another stackoverflow page! – 김범석 May 23 '20 at 06:27

0 Answers0