0

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Heijs7
  • 27
  • 6
  • `matrix1 is not matrix2`, but `matrix1[1] is matrix2[1]`. Does that help? Also `matrix1[0] is not matrix2[0]` since you reassigned it. – wjandrea Apr 10 '20 at 18:28
  • Related: [How to deep copy a list?](https://stackoverflow.com/q/17873384/4518341) – wjandrea Apr 10 '20 at 19:17

1 Answers1

2

For example you have a list matrix1=[[1,2], [3,4]] and you assigned this to matrix2 = matrix1. When you assigned matrix1 to matrix2 it just share a reference it doesn't create new array. Now if you change any data in matrix1 or matrix2 changes will apply to both the lists.

But if you use slice operation it will create a new list matrix2 = matrix1[:]. Now if you change any data in matrix2 or matrix1 changes will apply respectively.

Note: slice operation produce shallow copy of list.

matrix2[0][0] = x this will change in both lists because of shallow copy shallow copy apply to only one level like matrix2[0] = [x,y].

If you don't want to change the data then you can use deepcopy. It copies every object recursively.

deadshot
  • 8,881
  • 4
  • 20
  • 39
  • Thank you very much, it's more clear for me now and what you said here: "matrix2[0][0] = x this will change in both lists because of shallow copy shallow copy apply to only one level like matrix2[0] = [x,y]." Makes so much sense with whats happening here. – Heijs7 Apr 11 '20 at 10:47