0

I am using a nested list to represent a matrix. Most of the entries will be zero, but some of them will be updated with other values. When I go to update an individual cell, however, it updates the entire column with the value.

rows = [0] * 3
matrix = []
for i in range(3):
    matrix.append(rows)
matrix[0][0] = 1
print(matrix)

Output I get: [[1,0,0], [1,0,0], [1,0,0]]

Output I want: [[1,0,0], [0,0,0], [0,0,0]]

What am I missing here? I think this has to do with some sort of deep copy vs shallow copy issue in the matrix.append(rows) call, but how can I fix it? How do I update just one cell at a time?

BLimitless
  • 2,060
  • 5
  • 17
  • 32
  • 1
    You're not using exactly the same syntax as the duplication question (since you don't use `*3` for the outer list), but you do build the same result by your loop that repeatedly appends the same thing to the matrix. – Blckknght Mar 01 '22 at 06:00
  • Try `matrix.append(list(row))` or `matrix.append([0]*3)` in the loop, and it will solve your issue. – Stef Mar 01 '22 at 10:26

0 Answers0