Reputation: 1555
Matrix = [[0]*3]*3
matrix[0][0] = 1
the result is
[[1,0,0],[1,0,0],[1,0,0]]
what's the issue here? is this a bug for matrix in Python?
Upvotes: 1
Views: 30
Reputation: 12990
Because all the indices in your matrix point to the same list (namely [0]*3
). You should create a new list for each index:
matrix = [[0]*3 for i in range(3)]
matrix[0][0] = 1
print(matrix)
# [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
Upvotes: 1