Any help? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Any help?

I found this bit of code in a challenge: x=[[0]*2]*2 x[0][0]=1 I don't understand why x becomes [[1,0],[1,0]] instead of [[1,0][0,0]]

1st Jan 2020, 6:30 PM
Luigio
Luigio - avatar
4 Answers
+ 3
[0]*2 creates the list [0, 0]. So [[0]*2]*2 creates [[0, 0], [0, 0]], but each of the [0, 0]s is the *same list* (I'll call that list l, so x = [l, l]). x[0][0] modifies the first element of that list (l) to 1, so now l is [1, 0], so x is [[1, 0], [1, 0]].
1st Jan 2020, 7:44 PM
Russ
Russ - avatar
+ 3
Do you mean where both [1, 1]s are the same list? If so, then x = [[1]*2]*2 would do it directly. If you want to change them to [1, 1] from [1, 0], x[0][1] = 1 changes x to [[1, 1][1, 1]].
1st Jan 2020, 8:06 PM
Russ
Russ - avatar
+ 1
Got it, thanks a lot :) Is there any way to produce [[1,1],[1,1]] in the same fashion?
1st Jan 2020, 8:03 PM
Luigio
Luigio - avatar
0
Okay thank you
1st Jan 2020, 8:15 PM
Luigio
Luigio - avatar