+ 20

I kept wondering why the output is [[3,2],[3,2]]

This code snippet why it keeps returning that out even though only index of [0][0] a = [[1,2]] * 2 print(a) a[0][0] = 3 print(a)

4th Oct 2019, 12:51 PM
BlackRose Mike
BlackRose Mike - avatar
4 Réponses
+ 4
By multiplying the list, ur creating 2nd member which refers same memory location as 1st member. So, if you change the value of 1st members, u will seesame value in 2 nd member also.. . U can cross check whether a[0][0] and a[1][0] referring to same memory location using id(a[0][0]) method. Same id value indicates that, they are referring to same memory location.
4th Oct 2019, 1:19 PM
Kuri
Kuri - avatar
+ 14
Thankx alot for clarifying this for me. But is it similar to something like a = b ??
4th Oct 2019, 1:29 PM
BlackRose Mike
BlackRose Mike - avatar
+ 7
Because they have the same reference. It doesn't kust create a new list with the elements [ 1, 2 ], but create a reference for it, which means a[0] and a[1] are pointing to the same list, so changing a[0][0] changes a[1][0]
4th Oct 2019, 1:17 PM
Airree
Airree - avatar
+ 2
Yes
4th Oct 2019, 2:14 PM
Kuri
Kuri - avatar