0
>>> m=[[-1]*2]*2
>>> n=[[-1,-1],[-1,-1]]
>>> m==n
True
>>> for i in range(2):
...  m[i][i]=10
...
>>> m
[[10, 10], [10, 10]]
>>> for i in range(2):
...  n[i][i]=10
...
>>> n
[[10, -1], [-1, 10]]

In the code block above, the assignment to the elements of n takes place as expected, but the assignment to elements of m is incorrect although both m and n before the assignment are equal, and the assignment takes place in the same manner. Can someone please clarify? Is this a bug in the usage of the * operator for the creation of the original list? This is Python 3.10.0.

user17144
  • 428
  • 3
  • 18
  • 1
    Good question (even though it is a duplicate). It is counter-intuitive behavior the first time you encounter it. I can see how it was especially confusing because of the equality test `m == n`. That just checks if corresponding entries are the same. It doesn't test if the lists have the same patterns of references. – John Coleman Nov 17 '22 at 15:31
  • Thank you for the clarification, and for not downvoting it or doing something similar because it was asked before or for any other reason. The downvote and the subsequent ban are what I dread. You never expect so much regulation on the net especially when a question is asked in good faith. I searched for quite some time for a solution before I posted my question. I was led to the original question when this question was marked as a duplicate, so the post worked for me. Yes, it was the "True" for m==n that confused me even more. – user17144 Nov 17 '22 at 15:54

1 Answers1

-2

Lists are used to store separate values, you can't declare a integer into a list and attempt to multiply it without specifying which number to multiply, and putting a integer in brackets m=[[-1]*2]*2 is how that can work, instead, do m=[-1] m[0]*2*2

Dwij
  • 11
  • 2