who can tell me what happens in this code? | Sololearn: Learn to code for FREE!

+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)

4/11/2021 3:40:44 PM

ice

4 Answers

New Answer

+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]))

0

why a[1][0]==5?

0

Interesting point '*' is there a trick?

0

this is very strange but anyway thanks for explaining 😊