JamesWang
JamesWang

Reputation: 1555

why setting one element value changes the values of other element in Python 2d matrix

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

Answers (1)

slider
slider

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

Related Questions