The difference between a deep copy and a shallow copy in a common interview question;
Shallow copy: Only copy the address, do not copy the value, two variables share the same object;
deep Copy: Copy the value, if the list is also a reference, the recursive copy;
A = [11,22= [33,44]c = [A, b]
D = C
ID (c)
ID (d)
As can be seen, the memory address of C and D is the same as the ID, this is a typical shallow copy, if you change the value of a, then C and D will change;
Import= copy.deepcopy (c) ID (d)
At this point the ID of D is different from C, and Copy.deepcopy () is a recursive copy, that is, changing the value of a, B or C, will not affect D, which is deep copy;
There is also an easily confusing copy.copy () function in the copy module, so what's the difference between it and copy.deepcopy ()?
E = Copy.copy (c)
At this point the IDs of E and C are different, if you change the value of C, E will not change, and if you change the value of a or B, then E will change accordingly, indicating that copy.copy () is only deep copy of the first layer, the second layer or a shallow copy;
The Copy object C at this point is a mutable list type, and if it is an immutable data type?
C2 == copy.copy (C2)
ID (C2)
ID (E2)
At this point we find that the address of C2 and E2 is the same, so we can analyze the copy law of Copy.deepcopy () and copy.copy (), namely:
copy.deepcopy () Always deep copy, supports recursive copy;
copy.copy () first determine the copy type, if variable, only deep copy the first layer, does not support recursive copy, if not mutable (such as tuples), shallow copy.
Deep copy and shallow copy in Python