The difference between a python copy, a deep copy, and a shallow copy

Source: Internet
Author: User

Write in front:
. Copy () copies and [:] copies in Python are shallow copies

In Python, an object assignment is actually a reference to an object. When you create an object and then assign it to another variable, Python does not copy the object, but only copies the reference to the object.
There are generally three ways to

eg:alist=[1,2,3,["a","b"]]

(1) Direct assignment, passing the reference of the object, the original list is changed, and the assigned B will make the same change.

>>> b=alist>>>print b[123, [‘a‘‘b‘]]>>> alist.append(5)>>>print alist;print b[123, [‘a‘‘b‘5][123, [‘a‘‘b‘5]

(2) Copy shallow copy, no sub-object copied, so the original data changes, the sub-object will change

>>> ImportCopy>>>C=Copy.copy (alist)>>> PrintAlist;Printc[1,2,3, [' A ',' B ']][1,2,3, [' A ',' B ']]>>>Alist.append (5)>>> PrintAlist;Printc[1,2,3, [' A ',' B '],5][1,2,3, [' A ',' B ']]>>>alist[3][' A ',' B ']>>>alist[3].append (' CCCC ')>>> PrintAlist;Printc[1,2,3, [' A ',' B ',' CCCC '],5][1,2,3, [' A ',' B ',' CCCC ']]#里面的子对象被改变了

(3) A deep copy that contains a copy of the object inside the object, so the change of the original object will not cause any changes in the deep copy of any child elements

>>> ImportCopy>>>D=Copy.deepcopy (alist)>>> PrintAlist;Printd[1,2,3, [' A ',' B ']][1,2,3, [' A ',' B ']]#始终没有改变>>>Alist.append (5)>>> PrintAlist;Printd[1,2,3, [' A ',' B '],5][1,2,3, [' A ',' B ']]#始终没有改变>>>alist[3][' A ',' B ']>>>alist[3].append ("CCCCC")>>> PrintAlist;Printd[1,2,3, [' A ',' B ',' CCCCC '],5][1,2,3, [' A ',' B ']]#始终没有改变

For security reasons, use a deep copy when copying is required.

Python copy, deep copy and shallow copy difference

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.