Home > Article > Backend Development > Deep copy and shallow copy in python
copy.copy Shallow copy only copies the parent object, and does not copy the internal child objects of the object.
copy.deepcopy deep copy object and its sub-objects
Example:
>>> import copy
>>> a=[1,2,3,4,['a' ,'b']]
>>> b=a # Pass the reference. It is equivalent to now that b and a point to the same memory area. Equivalent to c and a now being two separate memory areas
>>> d=copy.deepcopy(a) # Deep copy. It is equivalent to a completely independent memory area
& gt; & gt; & gt; a.append (5) #This is the outer object, that is, the parent object processing will affect the Copy shallow copy & gt; & gt; a [4]. append('c') # This is an internal sub-object and will not affect it. That is, it still points to a piece of
>>> print 'a',a
a [1, 2, 3, 4, ['a' , 'b', 'c'], 5]
>>> print 'b',b
b [1, 2, 3, 4, ['a', 'b', 'c' ], 5]
>>> print 'c',c
c [1, 2, 3, 4, ['a', 'b', 'c']]
>> > print 'd',d
d [1, 2, 3, 4, ['a', 'b']]
>>>
If copied, they are independent of each other .
Like copy.copy, a shallow copy is actually made because it is the parent object, so: the parent object is not affected and there are two separate areas.
Conclusion: Whichever one is copied is a separate memory area. It is separate from the original memory. No matter how you modify it, it won’t affect me