6.Python depth Copy

Source: Internet
Author: User
Tags shallow copy

Python depth copy

The process of assigning a variable value:

# -*-coding:utf-8 -*-__author__ = ‘xiaojiaxin‘__file_name__ = ‘shallowcopy_deepcopy‘#当拷贝数据足够多的时候,浪费空间# str1=[1,"jiaxin","john"]# str2=[1,"jiaxin","john"]# print(str1)# print(str2)

Copy method

str1=[1,"jiaxin","john"]str2=str1.copy()print(str1)print(str2)# [1, ‘jiaxin‘, ‘john‘]# [1, ‘jiaxin‘, ‘john‘]str2[0]=10;print(str1)print(str2)# [1, ‘jiaxin‘, ‘john‘]# [10, ‘jiaxin‘, ‘john‘]str3=[[1,2],"jiaxin",‘john‘]str4=str3.copy()print(str4)#[[1, 2], ‘jiaxin‘, ‘john‘]str4[1]="jiaxin01"print(str3)     #str3不变,str4改变print(str4)# [[1, 2], ‘jiaxin‘, ‘john‘]# [[1, 2], ‘jiaxin01‘, ‘john‘]


Shallow copy:

str5=[[1,2],"jiaxin",‘john‘]str6=str5.copy()   #等价于str6=str5[:],但是不等于str6=str5  很重要!!!!print(str5)print(id(str5[0]))print(str6)print(id(str6[0]))# [[1, 2], ‘jiaxin‘, ‘john‘]# [[1, 2], ‘jiaxin‘, ‘john‘]str6[0][1]=201    #str5,str6一起改变print(str5)print(str6)# [[1, 201], ‘jiaxin‘, ‘john‘]# [[1, 201], ‘jiaxin‘, ‘john‘]

Deep copy

# -*-coding:utf-8 -*-__author__ = ‘xiaojiaxin‘__file_name__ = ‘deep_copy‘import copy#深拷贝需要一个独立的模块来完成a=[[1,2],3,4]b=copy.deepcopy(a)print(id(a))print(id(b))b[0][0]=99print(a)print(b)#1080515447944#1080515539400# [[1, 2], 3, 4]# [[99, 2], 3, 4]

Full assignment:
B=a situation

a=[[1,2],3,4]b=aprint(id(a))print(id(b))b[0][0]=99print(id(a))print(id(b))print(a)print(b)# 818876113416# 818876113416# 818876113416# 818876113416# [[99, 2], 3, 4]# [[99, 2], 3, 4]

If you feel good, please have a comment to encourage the author, thank you!

6.Python depth 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.