+ 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
7 Réponses
+ 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
+ 3
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.
+ 1
@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.
+ 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
XXX good explained 👍