0

Why a[0][0]==a[1][0] ?

I thought the output would be [[2,3], [3,3]]. But it seems that a[0][0]==a[1][0]. https://code.sololearn.com/cMk9E0Oh0LJ4/?ref=app

8th Sep 2022, 12:57 PM
Levi
Levi - avatar
3 Answers
+ 3
The way you created the list, a[0] is indeed a[1] try print(a[0] is a[1]) and you will get True. you should do a = [[2,3] for _ in range(2)]
8th Sep 2022, 1:16 PM
Bob_Li
Bob_Li - avatar
+ 2
When you duplicate reference types, you copy references. Both members of your array reference the same array. If you change the one, you change the other.
8th Sep 2022, 1:15 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
The only thing I can think of here is that when you do the multiplication in the first line, it creates a second item in the outer list that points to wherever the item that was already there (in this case, the inner list) is stored, instead of creating another unique instance of it. In this way, when you change one, you inherently change the other, because they point to the same space in memory.
8th Sep 2022, 1:16 PM
Tyler McKechnie