0

So given a m*n matrix represented as columns, I'm supposed to increment one index at a time to fill a specified amount of row and column, say if I'm supposed to increment (2,0), it'll ONLY increment (2,0). So I wrote this code:

for i in range(row):
    for j in range(col):
        print("X")
        print(matrix)
        content = matrix[i][j]
        matrix[i][j]=content+1
        print("matrix ({},{}) = {}".format(i,j,matrix[i][j]))

I added several prints to debug the code, and on the first index it outputs:

X
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
matrix (0,0) = 1
[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]

it's supposed to increment (0,0) to 1 so it's supposed to look like this:

[[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

but as you can see....it increments an entire row at once... I don't know why it happened, did I miss something?

Lil Student
  • 17
  • 1
  • 4

1 Answers1

0

The problem is in the way you created the matrix, which you didn't show us. You probably did something like this:

matrix = [[0]*col]*row

What's not obvious from this is that this creates ONE list with 'col' zeros, and then creates 'row' references to that one list. There are not 'row' separate lists. When you change one of the lists, you'll see that in all of the rows. You need to do something like this:

matrix = [ [0]*row for _ in col ]

Or, as @Jan suggested, use numpy.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30