Deep copy and shallow copy in Python

Source: Internet
Author: User
Tags shallow copy

The difference between a deep copy and a shallow copy in a common interview question;

Shallow copy: Only copy the address, do not copy the value, two variables share the same object; deep Copy: Copy the value, if the list is also a reference, the recursive copy;
A = [11,22= [33,44]c = [A, b]
D = C
ID (c)
ID (d)

As can be seen, the memory address of C and D is the same as the ID, this is a typical shallow copy, if you change the value of a, then C and D will change;

Import= copy.deepcopy (c) ID (d)

At this point the ID of D is different from C, and Copy.deepcopy () is a recursive copy, that is, changing the value of a, B or C, will not affect D, which is deep copy;

There is also an easily confusing copy.copy () function in the copy module, so what's the difference between it and copy.deepcopy ()?

E = Copy.copy (c)

At this point the IDs of E and C are different, if you change the value of C, E will not change, and if you change the value of a or B, then E will change accordingly, indicating that copy.copy () is only deep copy of the first layer, the second layer or a shallow copy;

The Copy object C at this point is a mutable list type, and if it is an immutable data type?

C2 == copy.copy (C2)
ID (C2)
ID (E2)

At this point we find that the address of C2 and E2 is the same, so we can analyze the copy law of Copy.deepcopy () and copy.copy (), namely:

copy.deepcopy () Always deep copy, supports recursive copy; copy.copy () first determine the copy type, if variable, only deep copy the first layer, does not support recursive copy, if not mutable (such as tuples), shallow copy.

Deep copy and shallow copy in 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: 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.