Python base assignment/deep copy/shallow copy

Source: Internet
Author: User
Tags shallow copy

First, whether it's an assignment or a depth copy, it's a distinction between values that might change, that is, for numbers, for strings, it's meaningless to assign values.

So, let's get to those mutable like List set Dict tuple ... To be explored.

Assignment value:

There are two ways to modify N:

1 assigning values directly to n

>>> n=[1,2]>>> g=n>>> ID (n)140529062430792>>>  ID (g)140529062430792>>> n=[1,3]>>> g[1, 2]>>> ID (n) 140529062430920>>> ID (g)140529062430792

2 Assigning a value to an element of n

>>> n=[1,2]>>> g=n>>> ID (n)140529062430728>>>  ID (g)140529062430728>>> n[1]=3>>> g[1, 3]>>> ID (n) 140529062430728>>> ID (g)140529062430728

Shallow copy

>>> Import copy>>> name=[' Tong ', ' Yang '
>>> N=[1,name]
>>> g=copy.copy (N)
>>> g
[1, [' Tong ', ' Yang ']
>>> ID (N)
140529062259976
>>> ID (g)
140529062259848# two variables (n and g) have different addresses

When modifying the element of the name of N:

>>> name[1]='Hua'>>>n[1, ['Tong','Hua']]>>>g[1, ['Tong','Hua']]>>>ID (n)140529062259976>>>ID (g)140529062259848#the values of N and G are the same, and the memory address has not changed

  shallow copy will only copy one layer, so the values of N and G have changed in the example above .

Deep copy

>>> name=['Tong','Yang']>>> n=[1, name]>>> g=copy.deepcopy (n)>>>g[1, ['Tong','Yang']] #g的第二个元素已经不是变量name了. >>>ID (n)140529062430728>>>ID (g)140529062259976#n differs from G's address

When you modify the element of name:

 >>> name[1]= " hua   '  >>> 

  Deep copy will copy all layers, and the values of the variables will be directly output to replace the variables.

This article refers to the following: http://www.cnblogs.com/wupeiqi/articles/5133343.html

Python base assignment/deep copy/shallow 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.