Python shallow copy and deep copy usage examples

Source: Internet
Author: User
Tags reference shallow copy

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

?

1 2 3 4 5 6 7 8 9 10 11 12-13 >>> person=[' name ', [' savings ', MB]] >>> hubby=person[:] >>> wifey=list (person) >> > [ID (x) for x in Person,hubby,wifey] [3074051788L, 3074061740L, 3074061996L] >>> [ID (y) for x in Person,hubby , Wifey for y in x] [3074319552l,3073979916l,3074319552l,3073979916l,3074319552l,3073979916l] >>> hubby[0]= ' Joe ' >>> wifey[0]= ' Jane ' ([' Joe ', [' savings ', 100]],[' Jane ', [' savings ', 100]],[' name ', [' savings ', MB]]) > >> 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 identical to the object being copied.

If the constituent elements of the copied object are immutable types, the change of the copied object to this element is actually creating a new object.

If the constituent element of the copied object is a mutable type, then the change of the copied object to the element is actually modifying the contents of the memory space on the original object's memory space.

In this way, only hubby[1][1]=70 can result in the change of Wifey,person corresponding value.

I hope this article will help you with your 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.