python 2d list/array problem | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 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

23rd Dec 2020, 4:37 AM
KUMAR SHANU
KUMAR SHANU - avatar
7 Antworten
+ 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
23rd Dec 2020, 5:42 AM
XXX
XXX - avatar
+ 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.
23rd Dec 2020, 5:09 AM
Kevin Ôśů
+ 2
Kevin Ôśů Jan Markus I got it ­čĹŹ Thank you for your help.
23rd Dec 2020, 5:24 AM
KUMAR SHANU
KUMAR SHANU - avatar
+ 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.
23rd Dec 2020, 5:19 AM
Kevin Ôśů
+ 1
Kevin Ôśů if I use any other value instead of None. The problem is same
23rd Dec 2020, 5:23 AM
KUMAR SHANU
KUMAR SHANU - avatar
+ 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.
25th Dec 2020, 12:22 AM
AW4
AW4 - avatar
0
XXX good explained ­čĹŹ
23rd Dec 2020, 5:54 AM
KUMAR SHANU
KUMAR SHANU - avatar