python 2d list/array problem | Sololearn: Learn to code for FREE!

+1

python 2d list/array problem

I have this 2d list (list of list) initialized with same values. Now if I try to change first column in first row(arr[0][0]) it changes all the rows. https://code.sololearn.com/cip0ZaTS7HkH/?ref=app

12/23/2020 4:37:05 AM

KUMAR SHANU

10 Answers

New Answer

+6

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. 🤔

+4

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][0]=0.

+4

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

+2

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.

+2

Kevin ★ Jan Markus I got it 👍 Thank you for your help.

+2

XXX Okay, now I got it. 🙂👍

+1

Kevin ★ if I use any other value instead of None. The problem is same

+1

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.

0

@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.

0

XXX good explained 👍