OregonDuck OregonDuck - 3 months ago 10
Python Question

python write cell to matrix in wrong way

I have a simple code for testing, my code supposed to only write matrix at (1,1) and (2,2), these two cells.

grid = [
[1,1,1,2,],
[1,9,1,2,],
[1,8,9,2,],
[1,2,3,4,]
]

n = 4
duplicate = [[0]*n]*n

for i in range(1,n-1):
for j in range(1,n-1):
cur = grid[i][j]
if (cur > grid[i-1][j]) and (cur > grid[i][j-1]) and (cur > grid[i+1][j]) and (cur > grid[i][j+1]):
print(i,j)
duplicate[i][j]="X"


print(duplicate)


My output:

1 1
2 2
[[0, 'X', 'X', 0], [0, 'X', 'X', 0], [0, 'X', 'X', 0], [0, 'X', 'X', 0]]


However, the output is supposed to be like this:

1 1
2 2
[[0, 0, 0, 0], [0, 'X', 0, 0], [0, 0, 'X', 0], [0, 0, 0, 0]]


What is wrong with my code?
Thanks a lot!

Answer

Usual mistake: [[0]*n]*n creates a list of n references to the same list [0]*n. You need do this to create n different lists: [[0]*n for _ in range(n)] so you can update each one of them independently.