I'm addicted to it, so make a note.
If you assign list to another variable in python, it will be "passed by reference".
x = [1, 2, 3]
y = x
y[0] = 999
x #The change to y also affected x.
>>> [999, 2, 3]
To avoid this (= pass by value), use copy.
from copy import copy
x = [1, 2, 3]
y = copy(x) # x[:]But good(Rather, this one is simpler)
y[0] = 999
x #Change to y did not affect
>>> [1, 2, 3]
So was the copy done completely? It's not. For example, nested lists are passed by reference.
from copy import copy
x = [[1, 2, 3], 4, 5]
y = copy(x)
y[0][0] = 999
x #Even though it's a copy!
>>> [[999, 2, 3], 4, 5]
Therefore, if you want to copy everything including nesting completely, use deepcopy.
from copy import deepcopy
x = [[1, 2, 3], 4, 5]
y = deepcopy(x)
y[0][0] = 999
x
>>> [[1, 2, 3], 4, 5]
When I tried it, it seems that it is automatically decided whether to execute a shallow copy or a deep copy. The following two differ in whether the second list in x contains 6 or not ** only **.
import numpy as np
x = [[1, 2, 3], [4, 5]]
y = np.copy(x)
y[0][0] = 999
x
>>> [[999, 2, 3], [4, 5, 6]]
import numpy as np
x = [[1, 2, 3], [4, 5, 6]]
y = np.copy(x)
y[0][0] = 999
x
>>> [[1, 2, 3], [4, 5, 6]]
Apparently, a deep copy is performed for something that can be converted into an n-dimensional array. I think it's just a straightforward idea as long as the matrix is represented by nesting lists. By the way, the same is true for 3D.
import numpy as np
x = [[[1, 0], [2, 0], [3]],
[[4, 0], [5, 0], [6, 0]]]
y = np.copy(x)
y[0][0][0] = 999
x
>>> [[[999, 0], [2, 0], [3]], [[4, 0], [5, 0], [6, 0]]]
import numpy as np
x = [[[1, 0], [2, 0], [3, 0]],
[[4, 0], [5, 0], [6, 0]]]
y = np.copy(x)
y[0][0][0] = 999
x
>>> [[[1, 0], [2, 0], [3, 0]], [[4, 0], [5, 0], [6, 0]]]
** deepcopy strongest! !! !! !! !! ** **
(For the time being) Officially, there are two problems with deep copy operations.
However, it doesn't hurt to have a slightly redundant copy for personal handling. Recursive processing isn't needed so often, and deepcopying may be a good choice in situations where you're addicted to it.
Recommended Posts