Python depth copy (shallow copy and deep copy in Python)

Source: Internet
Author: User

Objective

Yesterday to brush the public number to see a description of Py elegant grammar article, the heart itch to get home and began to try to learn the for else Statement,yield and PY version of the three-mesh writing. In this section of the list slice, the author's copy of the list is not understood.

# copy copy_items = items[::] or items[:]
Try

Start with a Python and build a list
l=[1,2,3]
Make a copy of it in two ways:

    1. My wording
      C=l
    2. The author's wording
      d=l[:]

Separately printed c and d , and there is no difference, carefully consider the author's intentions, think there should be some deep-seated considerations.
You then use a id() separate view of the memory addresses on both sides, which results in a different print.

>>> ID (l)39179656l>>> ID (c)39179656l>>> ID (d)39179272L

The memory address used for direct assignment is the same as the memory address of the c original list, and the l memory address copied with the slice method is d not the same.
I try to change l the values to see the results.

>>> l.append ('z')>>> l['z'  ]>>> c['z']>>> d[ 1, 2, 3]

At this point the difference is shown, using direct assignment c because the l same memory address is pointed to the original list, so when the l value is modified, the printing c also finds the same change.

Explore

Just a little bit. How to copy a list, found that this is a proper noun, called "deep copy" (copy,deepcopy). My original direct assignment is simply to pass a reference to the memory address into a new object, not even a shallow copy.
Python's copy has a dedicated module called copy .

Shallow copy
Import copy; >>> l=[1,2,3,[4,5],6]>>> c=copy.copy (l)>>> ID (l)39195912L >>> ID (c)39238600L

Clearly from memory references, at least memory addresses are different, and changes to the l content should not be affected c .

>>> l.append ('z')>>> l['z'  ]>>> c[1, 2, 3, [4, 5], 6]

But after all, it's a shallow copy, just a copy of the outermost object, not a copy of the sub-object.

>>> ID (l[3])39195784l>>> ID (c[3])39195784l>>> l[3].append (' AZ ' )>>> l['az'z' >>> c['az'], 6]

It is true that the memory address of the child object of the original list is the same as the l c memory address of the corresponding sub-object of the shallow copy, so it also affects when the sub-object content of the original list changes c .

Deep copy

With a shallow copy experience, create a deep copy object and d look at the memory address of the outer object and the child object first.

>>> l=[1,2,3,[4,5],6]>>> d=copy.deepcopy (l)>>> ID (l) 39236296l>>> ID (d)39195912l>>> ID (l[3])39179656l>>> ID (d[3]) 39236040L

The results clearly show that l both the original list and the deep copy object d have different memory addresses for the outer and sub-objects.

>>> L.append ('Z')>>>l[1, 2, 3, [4, 5], 6,'Z']>>>d[1, 2, 3, [4, 5], 6]>>> L[3].append ('AZ')>>>l[1, 2, 3, [4, 5,'AZ'], 6,'Z']>>>d[1, 2, 3, [4, 5], 6]

Check the results again and verify my guess.

Summarize

Python is a scripting language that declares an object that actually creates an address store object in memory and points the object name to that memory address. When you assign a value using PHP's Assignment method, you simply create a new object name and point to the same memory address.
The list copy method used by the author of the Py Elegant grammar c=l[:] is a shallow copy, but the wording is relatively copy.copy() concise.
The code of the Copy module reveals that the deepcopy is recursive based on copy.

# C:\Python27\Lib\copy.py def deepcopy (x, Memo=none, _nil== _reconstruct (x, RV, 1, Memo); def _reconstruct (x, info, deep, memo=None): ... if  = deepcopy (args, Memo);..

Note: This article was posted in 2017-08-03, the original address of my GitHub page.

Python depth copy (shallow copy and deep copy in 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.