python--shallow copy and deep copy

Source: Internet
Author: User
Tags shallow copy

Before, I explained the problem of object assignment in Python in python– memory management, and we already know that when we create an object and assign it to another variable, we don't actually copy the object. Instead of just adding a reference to the object (see the link given in the section "Reference count" for blog post)

Assignment is a reference, not a copy

Review it, like the following example

2b = aprint(idid# >>> 4443297952 4443297952# 对于列表这种可变类型,也是一样的c = [12"we"]d = cprint(idid# >>> 4362693768 4362693768

Because there is no real copy, so "one change"

c = [12"we"]d = cd[13# >>> [13"we"# >>> [13"we"]
Shallow copy 1. Three copies of the method

But this is obviously not enough to meet the actual requirements, so we need the corresponding copy method, in the list, for example, there are three copies of the method

# Slice [:]A = ["We",1,2]b = a[:]b[0] ="You"Print (b,ID(b))# >>> [' You ', 1, 2] 4427664520Print (A,ID(a))# >>> [' we ', 1, 2] 4427664648# Copy () functionA1 = ["We",1,2]B1 = A1.Copy() b1[1] =3Print (B1,ID(B1))# >>> [' we ', 3, 2] 4537855112Print (A1,ID(A1))# >>> [' we ', 1, 2] 4537855240# Factory functions, such as List (), Dictionary dict (), etc.A2 = ["We",1,2]B2 =List(A2) b2[2] =3Print (B2,ID(B2))# >>> [' we ', 1, 3] 4507116488Print (A2,ID(A2))# >>> [' we ', 1, 2] 4507081864

As can be seen from the above three examples, three copy methods have achieved the same effect, the copy generated a new object, changes to the new object will not affect the original object. However, it is important to note that the elements of the list in our example can all be atomic (strings, numbers, and so on), and if they are mutable, the situation is not necessarily the case.

2. Copying objects, but not copying the contents of the objects

Or the above example, let's go one step further

a = [123aforina# >>> [4412074112, 4412074144, 4412074176]forin# >>> [4412074112, 4412074144, 4412074176]

It is not hard to see that B is actually a copy of a, but the content of B is all a reference to the content of a, not copied.

We will create this new object, but the object's content Q is a copy of the original object's reference, called a shallow copy.

However, if we re-change the elements of the new object, if the element is atomic, such as a number, a string, a tuple. So it's actually a new object, and then the alias, which references the new object. So, it looks as if it's actually copying the contents of the object, but it doesn't. It's a bit of a detour, so let's look at the following example, which may be clearer.

a= [1,2,3]b =a. Copy ()# According to the above example, the ID of each element of a and B must be the same at this point .print ([ID (x) forXinch a])# >>> [4339624064, 4339624096, 4339624128]# A new object (integer 0) is created, and the name B[0] refers to this objectb[0] =0 # At this point, the address of b[0] changed.print ([ID (x) forXinchb])# >>> [4339624032, 4339624096, 4339624128]# But, a doesn't change #print ([ID (x) forXinch a])# >>> [4339624064, 4339624096, 4339624128]

I think the above explanation explains why these copy methods, like slices, copy() functions, and factory functions, do seem to be creating new object content (because the original object is not affected by changing the contents of the copied object), but his mechanism is still a shallow copy, and the contents of the copied object remain a reference to the original object's corresponding content.

What's the use of knowing this? For example, when the object in D contains a list, we will not assume that the change to the list element of the copied object will ensure that the original object is unchanged.

a = [‘I‘, [1, 2]]b = a.copy()b[1][0] = 0print(b) # >>> [‘I‘, [0, 2]]# 这里特别小心,b的内容变了,而且因为b的内容只是对a中相应内容的引用,所以a也变了。print(a) # >>> [‘I‘, [0, 2]]
Deep copy

Then, of course, you will encounter scenes that need to copy all of the object's contents while copying the object. In other words, from the inside out, all copies from small to large. We refer to this "thorough" copy, called "Deep copy."

The deep copy method is also simple, introduce the copy library, use the copy.deepcopy() function to

import copya = [‘I‘, [12forin# >>> [4380781288, 4381566152]forin# >>> [4380781288, 4381565384]

It should be noted that the content of the object is atomic, such as in the example above, the first element of the list is a string, then there is no deep copy problem, use a shallow copy.

In fact, this certainly does not affect our application, because the atomic type object, when we make the modification, will re-create the object, and then reference, this has already said. Like what

import copya = [‘I‘, [1, 2]]b = copy.deepcopy(a)b[0] = "You"b[1][1] = 3# 随意改变b,a完全不受影响print(b) # >>> [‘You‘, [1, 3]]print(a) # >>> [‘I‘, [1, 2]]

python--shallow copy and deep 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.