+ 1

Question on List

x = [[0]*2]*2 x [0][0] = 1 print (x) Why is the output of above [[1,0], [1,0]] and not [[1,0], [0,0]]?

11th Mar 2020, 12:41 PM
Rini
Rini - avatar
2 Answers
+ 3
This is a reference issue: * used with lists creates a list with has x times the content of the multiplied list in there. Not a copy of the content - the actual content of the copied list - as references. So you end up changing the same list, that is referred to in several places, instead of a similar one. Instead of a longer answer (this problem and others of the sort are often asked about here), let me refer you to this: https://code.sololearn.com/c89ejW97QsTN/?ref=app After reading it, you should be able to figure out most or all similar problems.
11th Mar 2020, 1:33 PM
HonFu
HonFu - avatar
0
Thanks a lot!
11th Mar 2020, 7:16 PM
Rini
Rini - avatar