Why did the value of a variable change without changing the value in Python change?

Asked 2 years ago, Updated 2 years ago, 22 views

matrix = [[1,2,3],[4,5,6],[7,8,9]]

index = matrix

a,b=0,0

index[a][b] = matrix[a+1][b]

print(matrix)

If you output matrix from the above code, even though you did not change the matrix value

[[4, 2, 3], [4, 5, 6], [7, 8, 9]]

The matrix value changes. Why are the prices changing and how do we solve them?

python

2022-09-22 18:31

1 Answers

By index = matrix, the index also has the value that matrix points to.

So index and matrix are the same. If you operate the index in that state, the value that matrix points to changes.

If you want to copy, you have to use the copy module to deepcopy.

import copy
index = copy.deepcopy(matrix)


2022-09-22 18:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.