+ 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.
5 Answers
+ 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
+ 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.
+ 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
+ 1
This is a second copy of b. That can you see better here:
https://code.sololearn.com/cyJWI2m8f7YF/?ref=app