Python append () and deep copy, shallow copy

Light and dark copy
In Python, object assignments are actually references to objects. When you create an object and assign it to another variable, Python does not copy the object, but just copies a reference to the object, which we call a shallow copy.

In Python, in order to make the two variables complement each other when performing an assignment operation, you can use the deepcopy method in the copy module, which is called deep copy.

append () function
When an object of type list is appended, a reference to that object is actually appended.
id () function: Returns the unique identifier of the object, which can be analogized to the address of the object in memory.
 

>>> alist = []
>>> num = [2]
>>> alist.append (num)
>>> id (num) == id (alist [0])
True

As shown in the example above, when num changes (provided that id (num) does not change), the contents of alist will change accordingly. Often brings unexpected consequences. To avoid this situation, you can use deep copy to solve:

alist.append (copy.deepcopy (num))

Author: