+ 1

who can tell me what happens in this code?

a=[[0]*2]*2 b=[[0,0],[0,0]] a[0][0]=5 b[0][0]=5 print(a,b)

11th Apr 2021, 3:40 PM
ice
ice - avatar
4 Réponses
+ 3
Ok it's simple First of all know this [0]*2 = [0,0] Ok then by same logic a = [[0]*2]*2 = [[0,0]]*2 = [[0,0],[0,0]] And you allready declared b as [[0,0],[0,0]] Now next a[0] = [0,0] and a[0][0] = 0 You assigned a[0][0] = 5 so now in place of 0 a[0][0] have 5 but wait wait since a have two copies of same list ie [0,0]. Therefore they refer to same memory. Therefore when you change its values from any one point then every point which refers to same location will changed Try Printing their ID to understand it in better way print(id(a[0][0])==id(a[1][0]))
11th Apr 2021, 3:58 PM
Ayush Kumar
Ayush Kumar - avatar
0
why a[1][0]==5?
11th Apr 2021, 3:43 PM
ice
ice - avatar
0
Interesting point '*' is there a trick?
11th Apr 2021, 4:26 PM
Amir
Amir - avatar
0
this is very strange but anyway thanks for explaining 😊
11th Apr 2021, 4:31 PM
ice
ice - avatar