Shallow copy and deep copy of Python

Source: Internet
Author: User

1. Shallow copy

1> assignment: From the following example we can see that the memory address of the new variable after the assignment has not changed, in fact, the assignment operation in Python does not open up new memory space, it just copies the reference of the new object, that is, in addition to the name of B, there is no other memory overhead, If you modify the value of a, it will affect the value of B, similarly, if you modify the value of B, it will also affect the value of a.

2> a shallow copy is a copy of the reference, it only copies the sub-object, so that ID (a)!=id (c), then the resource inside the object is still a reference, so the internal ID (a[0]) ==id (c[0]), ID (a[2][0]) ==id (c[2][0]), If there are nested elements, modify the values of the shallow copy, and the original variable is also modified

2. Deep copy

A deep copy is a copy of an object resource, ID (a)!=id (d), and its internal resources are not nested. ID (a[0]) ==id (d[0]), if there is a nested case, ID (a[2])!=id (d[2])

All parameters are passed by reference in Python.

If you modify the parameters in the function, the original parameters are changed.

The original list will be changed after the list has been manipulated.

Shallow copy and deep copy of Python

Related Article

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: 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.