10 AnswersNew Answer
you can avoid the behaviour with arr = [[None for i in range(3)] for j in range(3)] instead of arr =[[None]*3]*3 While the first variant creates separate instances of the fields, the second variant creates only the first row of the matrix, and the second and third rows are just references to the first row. But I cannot explain why in the first row the second and third element are individual elements and not just a reference to the first element. Perhaps somebody can explain this. 🤔
Kevin ★ But with arr =[[None]*3]*3 it is strange to me that if the operator * produces a shallow copy why not all 9 fields become 0 if you set arr=0.
Jan Markus the reference is not to None, but to the array formed from `[None] * 3`. This is because None is not a reference type while list is. That is why when you change 1 array, all arrays are changed. See this https://code.sololearn.com/ciT1hkyu0J84/?ref=app EDIT: KUMAR SHANU another thing. Jan Markus gave you a solution for the problem. Just wanted to add that instead of arr = [[None for i in range(3)] for j in range(3)] just `arr = [[None] * 3 for i in range(3)]` will also work. I edited my code so you can see why
The lists after the multiplication are clones of each other. They refer to the same object. That's how * works here, it's called shallow copy.
Kevin ★ Jan Markus I got it 👍 Thank you for your help.
XXX Okay, now I got it. 🙂👍
Kevin ★ if I use any other value instead of None. The problem is same
if u say [[arr]*3]*3], it will multiply everything by 3. u have to say for i in y do *3 if u want to specify.
@Jan Markus I don't know if I understand you correctly but it seems to be due to the fact that None is inmutable while lists are not.
XXX good explained 👍