Deep copy and shallow copy in Python

Source: Internet
Author: User
Copy.copy a shallow copy copies only the parent object and does not copy the inner child objects of the object.

Copy.deepcopy deep Copy Copy objects and their sub-objects

Example:

>>> Import Copy

>>> a=[1,2,3,4,[' A ', ' B ']

>>> B=a # Pass reference. Equivalent to now B and a point to the same piece of memory area

In that case, any modification of a B will be synchronized

>>> C=copy.copy (a) # shallow copy. The equivalent of C and a are now two separate memory areas

>>> D=copy.deepcopy (a) # deep copy. Equivalent to a completely separate memory area

>>> A.append (5) # This is on the outer object that the parent object processing affects the copy shallow copy

>>> a[4].append (' C ') # This is an internal sub-object that does not affect. That is, it is still pointing to a piece

>>> 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 they are copied, they are independent of each other.

Like Copy.copy, it's actually a shallow copy, because it's a parent object. Therefore: The parent object is not affected. is a separate two-block area.

Conclusion: which copy of which is a separate memory area. is separate from the original memory. You can't change it, and it won't affect me.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.