+ 6

a=[[0]*2]*2 a[0][0]=5 out: [[5,0],[5,0]]

I don't understand this (a challenge question): a=[[0]*2]*2 a[0][0]=5 print(a) Output: [[5,0],[5,0]] Can someone please explain to me why it's not: [[5,0],[0,0]] [solved] (Thanks to Abhay for the link) A quote from NPE (stackoverflow): This has to do with the fact that lists are objects, and objects are stored by reference. When you use * et al, it is the reference that gets repeated, hence the behaviour that you're seeing.

5th Sep 2021, 12:39 PM
Arsalan [Inactive]
Arsalan [Inactive] - avatar
5 Antworten
+ 4
Here is the step by step working a=[0]*2 #[0,0] a=[[0]*2] #[[0,0]] a=[[0]*2]*2 #[[0,0],[0,0]] now assign new value to a a[0][0]=5 So the output is [[5,0],[5,0]] I hope you get it
5th Sep 2021, 12:53 PM
Myo Thuzar
Myo Thuzar - avatar
+ 3
Myo Thuzar Thanks. But i didn't; a = [[0,0],[0,0]] a[0][0] = 5 Output: [[5,0][0,0]] Why here output is different.
5th Sep 2021, 1:00 PM
Arsalan [Inactive]
Arsalan [Inactive] - avatar
+ 2
first one is When you assign 5 to a[0][0] process restart from top. It works like a=[0]*2 #[5,0] ,a[0][0] is 5 a[0][1] is 0 change in here and all the rest are following on it a=[[0]*2] #[[5,0]] a=[[0]*2]*2 #[[5,0],[5,0]] Second one a=[0,0][0,0] a[0][0]=5 output is [5,0][0,0] it has no step by step flow like above one directly change to a[0][0] to 5 it doesn't change a[1][0] P.s :the way I explain you is the way I understand on it
5th Sep 2021, 1:06 PM
Myo Thuzar
Myo Thuzar - avatar
+ 1
This is a second copy of b. That can you see better here: https://code.sololearn.com/cyJWI2m8f7YF/?ref=app
5th Sep 2021, 1:06 PM
JaScript
JaScript - avatar