GeorgeGray
GeorgeGray

Reputation: 25

The slice does not copy the list items, but the link to the list

matrix_a = [[5, 0.9, 0.3, 0.2],
        [0.2, 8, 0.7, 0.5],
        [1, 0.3, 5.5, 0.4],
        [0.2, 0.5, 0.7, 6]]
 matrix_d = [7,
        9,
        -5,
        6]
def kramer_method(matrix, solution, determinant):

for i in range(4):
    temp_matrix = matrix[:]
    for t in range(4):
        temp_matrix[t][i] = solution[t]
    print(temp_matrix)
print(id(temp_matrix) == id(matrix))
return
kramer_method(matrix_a,matrix_d,determinant)

result:

[[7, 0.9, 0.3, 0.2], [9, 8, 0.7, 0.5], [-5, 0.3, 5.5, 0.4], [6, 0.5, 0.7, 6]]
[[7, 7, 0.3, 0.2], [9, 9, 0.7, 0.5], [-5, -5, 5.5, 0.4], [6, 6, 0.7, 6]]
[[7, 7, 7, 0.2], [9, 9, 9, 0.5], [-5, -5, -5, 0.4], [6, 6, 6, 6]]
[[7, 7, 7, 7], [9, 9, 9, 9], [-5, -5, -5, -5], [6, 6, 6, 6]]
False

The quetion is: why is the temp_matrix list not taking the original matrix values ​​at the start of the loop?

Upvotes: 1

Views: 30

Answers (1)

Bryce
Bryce

Reputation: 160

Taking a slice of a list does copy the list. It does what is known as a shallow copy. This means that while temp_matrix is a copy of the original list, it does not copy the elements. So if you did something like temp_matrix.append([1,2,3]), it would not change matrix. Since it does not copy the elements, if you modify one of those temp_matrix[0].append(5), it would modify both temp_matrix and matrix since it is modifying the lists inside which were not copied.

What you will want to do is use the copy module. Specifically, you will want to import copy, and rather than use temp_matrix = matrix[:], you would use temp_matrix = copy.deepcopy(matrix). That page about the copy module also explains a bit more about what a deep copy is needed over a shallow copy as you had originally.

Upvotes: 1

Related Questions