Python shallow copy and deep copy usage examples

Source: Internet
Author: User
The examples in this paper describe Python shallow copy and deep copy usage. Share to everyone for your reference. The specific analysis is as follows:

>>> person=[' name ', [' savings ',100]]>>> hubby=person[:]>>> wifey=list (person) >> > [ID (x) for x in person,hubby,wifey][3074051788l, 3074061740L, 3074061996l]>>> [ID (y) for x in Person,hubby,w Ifey for y in x][3074319552l,3073979916l,3074319552l,3073979916l,3074319552l,3073979916l]>>> hubby[0]= ' Joe ' >>> wifey[0]= ' Jane ' ([' Joe ', [' savings ', 100]],[' Jane ', [' savings ', ' 100]],[' name ', [' savings ',]]) > >> hubby[1][1]=70>>> Hubby,wifey,person ([' Joe ', [' savings ', 70]],[' Jane ', [' savings ', 70]],[' name ', [' Savings ', 70]])

A shallow copy creates a new object, but its object reference is exactly the same as the copied object.

If the constituent element of the copied object is an immutable type, the Copy object changes to this element, in effect creating a new object.

If the constituent element of the copied object is a mutable type, the copy object changes the element, which in effect modifies the contents of the memory space on the memory space of the original object.

In this way, only hubby[1][1]=70 can cause changes in the corresponding values of Wifey,person.

Hopefully this article will help you with Python programming.

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