About List in Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

About List in Python

I don’t know how it works. Can someone explain it for me please. Why x = [[1, 0], [1, 0]] after I assign x[0][0] = 1 ? https://code.sololearn.com/ck5II3snR97a/?ref=app Thanks!

8th Oct 2019, 4:43 PM
Anh Hoàng Thế
Anh Hoàng Thế - avatar
4 Answers
+ 3
Anh Hoàng Thế In addition to what the others have already explained, the outer multiplication appears to be referencing a copy of the first list instead of creating a unique reference to a new list. I created a new variant of your code to demonstrate this further. https://code.sololearn.com/cU7W5mYzTCV9/?ref=app
8th Oct 2019, 9:39 PM
David Carroll
David Carroll - avatar
+ 4
Although the list in your question looks like a list with two lists in it, it's in reality a list with *one* list in it - the same list twice! So if you change one, you change the other too. Because it isn't really an *other*.
8th Oct 2019, 5:18 PM
HonFu
HonFu - avatar
+ 3
It works like this because you multiply by two. If you use x=[[0,0],[0,0]] as initialisation instead it works as expected.
8th Oct 2019, 5:11 PM
Lord HN
Lord HN - avatar
+ 2
Thank you all very much! 😃
8th Oct 2019, 11:25 PM
Anh Hoàng Thế
Anh Hoàng Thế - avatar