a=[[0]*2]*2

for i in range(3):

x,y,z=map(int,input().split())

a[x-1][y-1]=z

print(a)

Input:

1 1 4

1 2 1

2 2 2

output:

[ [ 4,2 ] ,[ 4 ,2 ] ]

But the op should be [ [ 4,1] ,[0,2] ] right?

What is going wrong here?

a=[[0]*2]*2

for i in range(3):

x,y,z=map(int,input().split())

a[x-1][y-1]=z

print(a)

Input:

1 1 4

1 2 1

2 2 2

output:

[ [ 4,2 ] ,[ 4 ,2 ] ]

But the op should be [ [ 4,1] ,[0,2] ] right?

What is going wrong here?

Its because of python’s pass by object reference

Use instead - a=[ [0]*2 for i in range(2) ]

Refer here for more details:

2 Likes

Thanks for clarifying : )