Deep and latent copies in Python

Source: Internet
Author: User

>>> a = [' Ace ', [' age ',10]]>>> b = a[:]>>> c = List (a) >>> for item in a: ...     Print (ID (item))     ... 140281621219736140281621134800>>> for item in B:    print (ID (item))     ... 140281621219736140281621134800>>> for item in C:    print (ID (item))     ... 140281621219736140281621134800

As you can see, the centralized copy here is just a pointer-like reference. Change to try?

>>> b[0] = ' bog ' >>> b[' bog ', [' age ', 10]]>>> a[' Ace ', [' age ', 10]]>>> c[' Ace ', [' age ' , 10]]>>> c[0] = ' cat ' >>> a[' Ace ', [' age ', 10]]>>> b[' bog ', [' age ', 10]]>>> c[' cat ', [ ' Age ', 10]]

AI, it's changed. Changing the list?

>>> a[' Ace ', [' age ', 10]]>>> b[' bog ', [' age ', 10]]>>> c[' cat ', [' age ', 10]]>>> a[1][ 1] = ' ago ' >>> a[' Ace ', [' Age ', ' ago ']]>>> b[' bog ', [' Age ', ' ago ']]>>> c[' cat ', [' Age ', ' ago '] >>> b[1][1] = ' agy ' >>> a[' Ace ', [' age ', ' agy ']]>>> b[' bog ', [' age ', ' agy ']]>>> c[' Cat ', [' age ', ' agy ']]>>> c[1][1] = ' cat! ' >>> a[' Ace ', [' age ', ' cat! '] >>> b[' bog ', [' age ', ' cat! '] >>> c[' cat ', [' age ', ' cat! ']

Emma, it's all changed. What a situation!

Haha, here's a summary!

found that the name string IDs in the list are different, but the age list IDs are the same.

This is because the strings in Python cannot be modified, so when you rename Tom and Anny, you re-create a ' tom ' and ' Anny ' object, replacing the old ' Jack ' object.

This explains that shallow copy (shallow copy), which duplicates the object, but still uses references to the elements in the object.

That deep copy is also playing full-time from memory space to open a new address to save a copy spicy!

How to use it?

>>> import copy>>> D = copy.deepcopy (a) >>> for item in a: ...     Print (ID (a))     ... 140281621133432140281621133432>>> for item in D:    print (ID (item))     ... 140281621219736140281621159160

see! It's not the same.

Deep and latent copies 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.