I recently searched for shallow and deep copies of the list, so make a note. (Reference: 8.10. Copy — Shallow copy and deep copy operations)
Normally, if you copy a list and change the value of one list, the value of the other list will also change ~~ (shallow copy) ~~
2017/9/17 postscript I received a comment. Thank you dlpyvim.
I don't think the example above is a shallow copy. A shallow copy is copy.copy (). The difference from copy.deepcopy () is whether to insert a reference or copy recursively if the object is inside an object.
>>> l = [1, 2, 3]
>>> l2 = l
>>> l
[1, 2, 3]
>>> l2
[1, 2, 3]
>>> l[2] = 4
>>> l
[1, 2, 4]
>>> l2
[1, 2, 4]
To avoid this, it seems that you can use the deepcopy () function (deep copy).
>>> l = [1, 2, 3]
>>> import copy
>>> l2 = copy.deepcopy(l)
>>> l
[1, 2, 3]
>>> l2
[1, 2, 3]
>>> l[2] = 4
>>> l
[1, 2, 4]
>>> l2
[1, 2, 3]
If you don't pay attention to this when you make an empty list, you will be in trouble because the value will be entered without permission.
>>> empty = [[]] * 5
>>> empty
[[], [], [], [], []]
>>> empty[0].append(1)
>>> empty
[[1], [1], [1], [1], [1]]
If you want to create such a two-dimensional empty list, you should use list comprehension notation.
>>> empty = [[] for x in range(5)]
>>> empty
[[], [], [], [], []]
>>> empty[0].append(1)
>>> empty
[[1], [], [], [], []]
Recommended Posts