Application of memory to data in Python

Source: Internet
Author: User

Python's use of memory

Shallow Copy

explain : copy of the reference (copy only the parent object);

Deep copy

explanation : A copy of the object resource;



Import module:

>>> Import Copy
>>> a = [1,2,3,[' A ', ' B ', ' d ']]>>> b = a>>> a[1, 2, 3, [' A ', ' B ', ' d ']]>>> b[1, 2, 3, [' A ', ' B ', ' d ']]>>> ID (a) 139712705065616>>> ID (b) 139712705065616# defines a two-tuple list, tag reference, and view memory address consistent, but not as a basis

Call the Copy.copy module to copy a shallow copy

>>> C=copy.copy (a)

Observe the address space of C, which is independent by copy

>>> c[1, 2, 3, [' A ', ' B ', ' d ']]>>> a[1, 2, 3, [' A ', ' B ', ' d ']]>>> ID (c) 139712705068784 #注意 > >> ID (a) 139712705065616 #注意

To add a value to a sequence:

>>> a.append (' d ') >>> a[1, 2, 3, [' A ', ' B ', ' d '], ' d ']>>> b[1, 2, 3, [' A ', ' B ', ' d '], ' d '] #b指向 The same address space >>> c[1, 2, 3, [' A ', ' B ', ' d ']] #c未改变

A shallow copy copies only the parent object:

>>> ID (a[3]) 139712704967456>>> ID (c[3]) 139712704967456>>> ID (a[4]) 139712705357456

#注意上述可变类型的子对象地址空间未改变,

Call the Copy.deepcopy module for copy deep copy

>>> d = copy.deepcopy (a)

View address space

>>> ID (a) 139712705065616>>> ID (d) 139712705065688>>> ID (a[3]) 139712704967456>> > ID (d[3]) 139712705068640 #此处是不一致的

To add a value to a sequence:

>>> a.append (' e ') >>> a[1, 2, 3, [' A ', ' B ', ' d ', ' d '], ' d ', ' E ']>>> d[1, 2, 3, [' A ', ' B ', ' d ', ' d '], ' d ']>>> a[3].append (' x ') >>> a[1, 2, 3, [' A ', ' B ', ' d ', ' d ', ' X '], ' d ', ' E ']>>> d[1, 2, 3, [' A ', ' B ', ' d ', ' d '], ' d ']

Copy of the object resource:

>>> ID (a[3]) 139712704967456>>> ID (d[3]) 139712705068640 #注意上述可变类型的子对象地址空间发生改变


This article from "thinking More than technology" blog, declined reprint!

Application of memory to data in Python

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.