1
m=int(input("enter the number of rows"))
n=int(input("enter the number of columns"))
mat=[0]
mat=[(mat*n)]*m
for i in range(m):
 for j in range(n):
  print "enter element of ",(i+1)," th row ",(j+1)," th column "
  mat[i][j]=int(input("?"))
  print mat
print mat

i used this code to enter a matrix, it didn't show any error but after inserting all the elements, when the matrix is printed, the 2 rows were the same...i cant see any error in the code :-(

output

enter the number of rows2
enter the number of columns3
enter element of  1  th row  1  th column 
?1
[[1, 0, 0], [1, 0, 0]]
enter element of  1  th row  2  th column 
?2 
[[1, 2, 0], [1, 2, 0]]
enter element of  1  th row  3  th column 
?3
[[1, 2, 3], [1, 2, 3]]
enter element of  2  th row  1  th column 
?4
[[4, 2, 3], [4, 2, 3]]
enter element of  2  th row  2  th column 
?5
[[4, 5, 3], [4, 5, 3]]
enter element of  2  th row  3  th column 
?6
[[4, 5, 6], [4, 5, 6]]
[[4, 5, 6], [4, 5, 6]]
0

1 Answer 1

2

This is a tricky one, that got me for a second.

This line here duplicates the reference to an anonymous object that comprises of mat*n:

mat=[(mat*n)]*m

So when you iterate through the rows, it updates each entry in every row, because they are all the same object.

As proof, using the id() function we can see that both rows in mat share the same memory!

>>> id(mat[0])
139943023116440
>>> id(mat[1])
139943023116440

Instead, consider a list comprehension to build your empty matrix:

>>> mat = [[0]*n for i in range(m)]
>>> mat[1][2] = 5
>>> mat
[[0, 0, 0], [0, 0, 5]]
Sign up to request clarification or add additional context in comments.

3 Comments

can't see any option for green ticks...maybe it will appear after the 'minimum time' (it's actually my first time in this site sorry)
@AJAYAJITH I believe he means if you accept his answer, a green check mark will appear underneath his post's upvotes.
Explanation on the green ticks is here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.