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]]
AJAY AJITH
  • 67
  • 9
  • This might be a duplicate of http://stackoverflow.com/questions/9459337/assign-value-to-an-individual-cell-in-a-two-dimensional-python-array – SomeGuyOnAComputer Nov 11 '15 at 05:24

1 Answers1

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