Deep copy and shallow copy of Python

Source: Internet
Author: User

In a nutshell, a shallow copy copies only the parent object and does not copy the sub-image.

Note: The difference between a shallow copy and a deep copy is simply that for a composite object, the so-called composite object is an object that contains other objects, such as lists, class instances. In the case of numbers, strings, and other "atomic" types, there is no copy that says that the original object's references are generated. Here's a code to demonstrate

Import copya=[[1,2],[3,4]]b=copy.copy (a) C=copy.deepcopy (a)

Now a B c is equal to [[1,2],[3,4]]

Now let's change the parent object of a.

A.append (5)

Now print the value of a B C and turn it into a

This is because both deep and shallow copies copy the parent object, which is independent of the parent object, so the value does not change.

Now let's change the sub-object of a.

A[0][0]=0

Now to print the value of a B C

A shallow copy copies only the parent object, so when A's sub-object changes, the sub-object of the shallow copy of B is changed, and the sub-object of the deep copy of C is independent, so it does not change

Deep copy and shallow copy of Python

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.