Deep Copy and Shallow Copy

In Python, object assignment is actually a reference to the object. When you create an object and assign it to another variable, Python does not copy the object, but only copies the reference to the object, which we call a shallow copy.

In Python, in order to make the two variables not affect each other during assignment operations, you can use the deepcopy method in the copy module, which is called a deep copy.

append() function

When a list-type object performs an append operation, it actually appends a reference to the object.

id()Function: returns the unique identifier of the object, which can be compared 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 content of alist changes accordingly. This often brings unexpected consequences. To avoid this, you can use deep copy to solve it:
alist.append( copy.deepcopy( num ) )

Original address: https://blog.csdn.net/u010099495/article/details/50276833