Python Basics: Shades of a copy

Source: Internet
Author: User
Tags shallow copy

For numeric, string-deep copies:
Import Copynum = 0copy_num = copy.copy (num) print ("These is normal copy"). Center ("*") Print (Num,id (num)) print (Copy_ Num,id (Copy_num)) print ("These is deep copy"). Center (*, ' * ') Deep_copy_num = copy.deepcopy (num) print (Num,id (num)) Print (Deep_copy_num,id (deep_copy_num)) *******************these is normal copy******************** (0, 3910788) # Original num ID (0, 3910788) #浅拷贝 Id********************these is deep copy********************* (0, 3910788) #原num ID (0, 3910788) # Deep Copy ID
For dictionaries, tuples, and list-depth copies:
Import copydic = {"CPU": [+,], "IO": [+,], "Disk": [+,], "Memory": [+,],}copy_dic = copy.copy (DIC) copy_d ic["CPU"][0]=30print ("These is normal copy"). Center ("*") Print (Dic,id (DIC)) print (Copy_dic,id (copy_dic)) print (" These is deep copy "). Center (' * ') Deepcopy_dic = Copy.deepcopy (DIC) deepcopy_dic[" CPU "][0]=40print (Dic,id (DIC)) Print (Deepcopy_dic,id (deepcopy_dic)) *******************these is normal copy******************** ({' Disk ': [70], ' CPU ': [+], ' io ': [[], ' memory ': []}, 39905584) #原dic ID ({' Disk ': [], ' CPU ': [+], ' io ': [], ' memory ': [70]}, 39 906736) #浅拷贝 Id********************these is deep copy********************* ({' Disk ': [[], ' CPU ': [+], ' IO ': [+], ' Me ' Mory ': [[]}, 39905584) #原dic ID ({' Disk ': [[], ' CPU ': [+], ' IO ': [], ' Memory ': []}, 39907168) #深拷贝 ID

As you can see, assignments, shallow copies, and deep copies are meaningless for numbers and strings because they always point to the same memory address.

For dictionaries, Ganso, and lists, the changes in the memory address of the assignment, the shallow copy, and the deep copy are different.

Assignment, just create a variable that points to the original memory address.

Python Basics: Shades of a copy

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.