Python copy and python copy

Source: Internet
Author: User

Python copy and python copy

Test environment: python 2.7

Use module copy. py

 

There are two methods in this module

Copy. copy () # Light copy

Copy. deepcopy () # Deep copy

What is the difference between shallow copy and deep copy:

The content of the first layer can only be copied in a shortest copy.

Deep copy can copy content from the outer to the inner n layers

 

See the example below:

list1 = [1,2,3,4]list2 = list1list1.append(99)print list2

Printed result: list2 = [1, 2, 3, 4, 99]

Note: In python, when a value is assigned to a variable of the reference type, the address is assigned to the variable.

Introduction to the reference type: http://www.cnblogs.com/gametesting/p/7159398.html

To solve this problem, we can use the slice operation:

List2 = list1 [:]

At the same time, we can also introduce the concept of copying only values.

 

list1 = [1,2,3,4]list2 = copy.copy(list1)list1.append(99)print list2

Printed result: list2 = [1, 2, 4]

When list1 is modified, list2 is not modified.

We can also copy. after copy () is complete, we can see that the memory addresses of the two are different by comparing id (list1) and id (list2, using the shortest copy function is equivalent to copying the value of list1 to a new memory area, and then assigning the value to list2.

 

However, when list1 = [1, 2, 3, 4, [1, 2] (when the operation object exceeds one dimension ),

We use the shortest copy, and it will be useless.

(Code omitted). After using the shortest copy function, you can find that the value of list1 is modified and the value of list2 is modified.

 

At this time, we need to use deep copy. deepcopy ()

list1 = [1,2,3,4,[1,2]]list2 = copy.deepcopy(list1)list1[4].append(99)print list2

Print the results to solve the problem perfectly

 

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.