Background: People often ask you the difference between deep copy and shallow copy, but still not clear exactly what the difference is

In this paper, we will do an experiment to understand the difference between them

Let’s say I have a list of A and I copy it to B

We can see that a new list is constructed for B, and in this case it looks as if A and B are independent, although they are not, as we’ll see later.

We want to get an identical list, and we can also use an assignment statement:

Summary: We can see that the assignment statement actually gets the same list, but it is referred to by variables A and B, respectively

The constructor and copy() result in the same shallow copy, except for a list() constructor that makes a shallow copy.

We can’t tell the difference between a shallow copy and a deep copy because our list is full of constants, so we can try to use a list nested with other data structures, such as the shallow copy first:

Reading: We can see, shallow copy all objects are Shared, we have modified the b will affect the value of a, as this will lead to disaster in some scenes, although shallow copy can save memory, but not to distinguish between Shared will surely there is a problem, a deep copy only do one thing, it is a variable data structure will not be Shared, Immutable structures are also shared. In this case, list as a mutable structure will be copied separately to B, while constants and tuples will be shared, because they won’t change anyway. Let’s look at deep copies:

As we can see, one more copy of the list is made, so that it is independent. Even if one of them is modified, the other one will not be affected.

Note: The above visualization was drawn using PythonTutor, which is handy for understanding memory