Deep copy and shallow copy in Python

Source: Internet
Author: User
Tags shallow copy

bytes

Python Bytes/str
Bytes in the Python3 as a separate data type, can not be spliced, not splicing, not splicing

>>> '€20'.encode('utf-8')b'\xe2\x82\xac20'>>> b'\xe2\x82\xac20'.decode('utf-8')'€20'

Decoding

>>> b'\xa420'.decode('windows-1255')'?20'

Deep copy and shallow copy
Deep copy creates a new object to reassign the memory address and copy the object contents. Shallow copy does not reassign the memory address, which points to the previous memory address. Shallow copy if the object has references to other objects, the contents of the child object are changed if the child object is modified.

import copy#这里有子对象numbers=['1','2','3',['4','5']]#浅copynum1=copy.copy(numbers)#深copynum2=copy.deepcopy(numbers)#直接对对象内容进行修改num1.append('6')#这里可以看到内容地址发生了偏移,增加了偏移‘6’的地址print('numbers:',numbers)print('numbers memory address:',id(numbers))print('numbers[3] memory address',id(numbers[3]))print('num1:',num1)print('num1 memory address:',id(num1))print('num1[3] memory address',id(num1[3]))num1[3].append('6')print('numbers:',numbers)print('num1:',num1)print('num2',num2)输出:numbers: ['1', '2', '3', ['4', '5']]numbers memory address: 1556526434888numbers memory address 1556526434952num1: ['1', '2', '3', ['4', '5'], '6']num1 memory address: 1556526454728num1[3] memory address 1556526434952numbers: ['1', '2', '3', ['4', '5', '6']]num1: ['1', '2', '3', ['4', '5', '6'], '6']num2 ['1', '2', '3', ['4', '5']]

Deep copy and shallow copy in Python

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.