Home  >  Article  >  Backend Development  >  Deep copy and shallow copy in python

Deep copy and shallow copy in python

巴扎黑
巴扎黑Original
2016-11-29 11:35:411036browse

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn