Copy list a to list b, just as you would copy a value Suppose you change only the middle element of list b.
copy_test.py
a = [1, 2, 3, 4, 5]
b = a
b[2] =5
print(a)
print(b)
For some reason, the element in the middle of list a also changes.
output
[1, 2, 5, 4, 5]
[1, 2, 5, 4, 5]
With the copy module, list a and list b are no longer linked.
copy_test2.py
import copy
a = [1, 2, 3, 4, 5]
b = copy.deepcopy(a)
b[2] =5
print(a)
print(b)
If you write a [:], everything in the element will be passed to list b.
copy_test3.py
a = [1, 2, 3, 4, 5]
b = a[:]
b[2] =5
print(a)
print(b)
<2019/12/22: From shiracamus> copy.deepcopy makes a complete copy, but copy.copy and slice copies are shallow copies. The effect remains in the case of multiple lists. → Solution 2 does not seem to work in the case of multiple lists.
copy_test4.py
a = [[1], [2], [3], [4], [5]]
b = a[:]
b[2][0] = 5
print(a)
print(b)
As you pointed out, multiple lists will link the results.
output
[[1], [2], [5], [4], [5]]
[[1], [2], [5], [4], [5]]
As expected, only the middle element of list b has changed. Solution 2 seems to be safer to use because it has the problem that it cannot be used with multiple lists.
output
[1, 2, 3, 4, 5]
[1, 2, 5, 4, 5]
Recommended Posts