I'm having a bad time trying to figure out what's going on here with the following shallow list.
In this code, after the modification on the shallow copy of the list (matrix2), where we replace an entire list in the list, the changes are reflected only for matrix2 but not matrix1 although matrix2 is a shallow copy of matrix1.
>>> matrix1 = [[1, 2], [3, 4]]
>>> matrix2 = matrix1[:]
>>> matrix2[0] = [5, 6]
>>> matrix2
[[5, 6], [3, 4]]
>>> matrix1
[[1, 2], [3, 4]]
In this part of the code the result is different because the modification of a value in one the list of the list is reflected for both matrix.
>>> matrix2[1][0] = 1
>>> matrix2
[[5, 6], [1, 4]]
>>> matrix1
[[1, 2], [1, 4]]
What i found is the following:
This happens because a list does not really contain objects themselves, but references to those objects in memory. When you make a copy of the list using the [:]
notation, a new list is returned containing the same references as the original list.
Can you help me to figure out what the above text really means? maybe i'm missing something here and i can't find the answer myself.