Python shallow copy and deep copy example

After the following code is run, the values ​​of the four variables a, b, c, and d are described incorrectly?

import copy
a = [1, 2, 3, 4, ['a', 'b']]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
a.append(5)
a[4].append('c')

A  a ==  [1,2, 3, 4, ['a', 'b', 'c'], 5]
B  b ==  [1,2, 3, 4, ['a', 'b', 'c'], 5] 
C  c ==  [1,2, 3, 4, ['a', 'b', 'c']]
D  d ==  [1,2, 3, 4, ['a', 'b', 'c']]

—————————————————— Thinking about the dividing line ——————————————————————

Answer: D

For a clearer explanation, I will use a picture to illustrate, first let's look at the actual storage of the list a in the computer

 

First, let's take a look at the situation of b. b actually points to the same value as a, just like a person's first and last name, but they are called differently, but they are still the same person

 

Next, look at the situation of c. The situation of c is the same as the situation of a.copy(), which is what we call shallow copy (shallow copy). Shallow copy will only copy the parent object, not the child object. In layman's terms, it will only be copied to the second layer

 

If the parent object changes, c will not change, because all the parent objects it has copied will change if the child object changes. For example, c[4] and a[4] are actually a variable list, and they both point to Sub-objects, if the sub-objects change, they must all change, such as becoming ["a", "d"], then the values ​​they point to will become a and d.

Look at the situation of d again, this is what we call deep copy, no matter what operation a performs, d will not be changed, they already point to different values ​​(here refers to the different storage locations in memory).

 

 

Summarize:

b=a, just changed a name, how a changes b can change,

c is a shallow copy, only part of the value of a is copied, and some values ​​are still shared, so c will be changed when operating on the subobject of a

d is a deep copy, which completely copies all the values ​​of a and has nothing to do with a, and any operation on a will not affect d

 

Guess you like

Origin blog.csdn.net/m0_66307842/article/details/127474728