When dealing with specific types such as list and dictionary, variables refer to an entity, unlike a value entity. The nature of the variables can be confirmed from the execution results of the following programs.
l1 = []
l1.append(0)
l2 = l1
l2.append(1)
print('l1 = ' ,l1)
print('l2 = ' ,l2)
Execution result
l1 = [0, 1] l2 = [0, 1]
After substituting the list l1
into the list l2
, I added a value only to l2
, but a similar value was added to l1
. This is because it is the reference information that holds both l1
and l2
, and the entities pointed to by the reference share the same thing.
The copy ()
method is used to solve the problem that the value itself is not copied just by making an assignment.
l1 = []
l1.append(0)
l3 = l1.copy()
l3.append(1)
print('l1 = ' ,l1)
print('l3 = ' ,l3)
Execution result
l1 = [0] l3 = [0, 1]
However, even if the copy ()
method is used, if the element of the list is a reference, the reference destination is not copied.
l4 = [[]]
l4[0].append(0)
l5 = l4.copy()
l5[0].append(1)
print('l4 = ' ,l4)
print('l5 = ' ,l5)
Execution result
l4 = [[0, 1]] l5 = [[0, 1]]
If you want to copy all the reference destinations of the elements included in the list, you can use the deepcopy ()
method included in the copy
package.
import copy
l4 = [[]]
l4[0].append(0)
l6 = copy.deepcopy(l4)
l6[0].append(1)
print('l4 = ' ,l4)
print('l6 = ' ,l6)
Execution result
l4 = [[0]] l6 = [[0, 1]]
Recommended Posts