Shallow copy, deep copy, and pythonshallow in python

Source: Internet
Author: User

Shallow copy, deep copy, and pythonshallow in python

Today, I encountered a strange problem when writing code. The problem is described as follows:

The Code declares a list and passes the list as a parameter to function1 (). In function1 (), del () is performed on the list to delete an element.

Function2 () also uses list as a parameter. After function1 () is called, function2 () is called again. The value of list has been changed, A bug occurs.

Directly run the Code:

list = [0, 1, 2, 3, 4, 5]def function1(list):    del list[1]    print(list)def function2(list):    print(list)function1(list)function2(list)

I don't want to change the list in function2 (). I checked the solution and said that the list can be copied:

newList = list.copy()function2(newList)

 

We found another method called deepcopy () in the process of finding the solution. The problem arises. What is the difference between deepcopy () and copy?

First, I checked the source code in the source code and found comments. Note:

"""Generic (shallow and deep) copying operations.Interface summary:        import copy        x = copy.copy(y)        # make a shallow copy of y        x = copy.deepcopy(y)    # make a deep copy of yFor module specific errors, copy.Error is raised.The difference between shallow and deep copying is only relevant forcompound objects (objects that contain other objects, like lists orclass instances).- A shallow copy constructs a new compound object and then (to the  extent possible) inserts *the same objects* into it that the  original contains.- A deep copy constructs a new compound object and then, recursively,  inserts *copies* into it of the objects found in the original.Two problems often exist with deep copy operations that don't existwith shallow copy operations: a) recursive objects (compound objects that, directly or indirectly,    contain a reference to themselves) may cause a recursive loop b) because deep copy copies *everything* it may copy too much, e.g.    administrative data structures that should be shared even between    copiesPython's deep copy operation avoids these problems by: a) keeping a table of objects already copied during the current    copying pass b) letting user-defined classes override the copying operation or the    set of components copiedThis version does not copy types like module, class, function, method,nor stack trace, stack frame, nor file, socket, window, nor array, norany similar types.Classes can use the same interfaces to control copying that they useto control pickling: they can define methods called __getinitargs__(),__getstate__() and __setstate__().  See the documentation for module"pickle" for information on these methods."""

However, I looked at it and looked at it. Continue to check the information on Baidu:

Https://iaman.actor/blog/2016/04/17/copy-in-python.

Copy is actually shallow copy, which is opposite to deep copy.

Conclusion:

1. There is no difference between shallow copy and deep copy for simple objects.

>>> Import copy >>> origin = 1 >>> cop1 = copy. copy (origin) # cop1 is the shallow copy of origin >>> cop2 = copy. deepcopy (origin) # cop2 is the deep copy of origin >>> origin = 2 >>> origin2 >>> cop11 >>> cop21 # cop1 and cop2 do not change their values with the origin >>> cop1 = cop2True >>> cop1 is cop2True

 

2. complex objects, such as listing,Shallow copyThe sub-list in is not "independent" from the original object.

If you change an element in the sub-list of the original object, Your copy will change along with it. This is different from our intuitive understanding of "replication.

>>> Import copy >>> origin = [1, 2, [3, 4] # There are three elements in origin: 1, 2, [3, 4] >>> cop1 = copy. copy (origin) >>> cop2 = copy. deepcopy (origin) >>> cop1 = cop2True >>> cop1 is cop2False # cop1 and cop2 look the same, but it is no longer the same object >>> origin [2] [0] = "hey! ">>> Origin [1, 2, ['Hey! ', 4] >>> cop1 [1, 2, [' hey! ', 4] >>> cop2 [1, 2, [3, 4] # removes an element from the sublist [3, 4] In the origin, observe cop1 and cop2

 cop1, That is, shallow copy is changed with the origin. Whilecop2That is, deep copy has not changed.

So the problem comes again. It's okay to use deepcopy directly. Why do we need copy?

The solution to this problem should begin with the python variable storage method. In python,Instead of assigning a value to a variable, it is better to create a reference to a specific value for the variable)

>>> A = [1, 2, 3] >>> B = a >>> a = [4, 5, 6] // assign a new value to a> a [4, 5, 6]> B [1, 2, 3] # After the value of a is changed, B does not change with a> a = [1, 2, 3]> B = a> a [0], a [1], a [2] = 4, 5, 6 // change the elements in the original list >>> a [4, 5, 6] >>> B [4, 5, 6] # After the value of a changes, B changes with

 

The code above changes the value of a. The difference is that the first section is to assign a new value to a, and the second section directly changes the elements in the list.

This strange phenomenon is explained below:

First put[1, 2, 3]As an item.a = [1, 2, 3]It is equivalent to attaching this itemaThis label. Whileb = aIt is to attach another item to this item.b.

 

First case:

a = [4, 5, 6]It is equivalentaTag from[1 ,2, 3]Torn down and pasted[4, 5, 6].

In this process,[1, 2, 3]This item does not disappear.bAlways stick well from beginning to end[1, 2, 3]Since this reference has not changed.bIs not changed.

 

Case 2:

a[0], a[1], a[2] = 4, 5, 6It is changed directly.[1, 2, 3]This item itself. Modify each part of it. After the internal modification is completed,[1, 2, 3]Itself becomes[4, 5, 6].

In this process,aAndbThey are not moved, and they are still pasted on that item. So naturallya bThe values are changed[4, 5, 6].

 

Use copy. copy (). The result shows that the ontology and copy are not independent. Sometimes change one of them, and the other will also change. That is, the example mentioned at the beginning of this article:

>>> Import copy >>> origin = [1, 2, [3, 4] # There are three elements in origin: 1, 2, [3, 4] >>> cop1 = copy. copy (origin) >>> cop2 = copy. deepcopy (origin) >>> cop1 = cop2True >>> cop1 is cop2False # cop1 and cop2 look the same, but it is no longer the same object >>> origin [2] [0] = "hey! ">>> Origin [1, 2, ['Hey! ', 4] >>> cop1 [1, 2, [' hey! ', 4] >>> cop2 [1, 2, [3, 4] # removes an element from the sublist [3, 4] In the origin, observe cop1 and cop2

Official explanation:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances ): A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the obj Ects found in the original. the two types of copy are only different in the face of complex objects. the so-called complex object refers to the object containing other objects (such as complex list and class ). In a new complex object created by shallow copy, each sub-object only points to the sub-object corresponding to itself in the original body. In the complex objects created by deep copy, the copy stored is the copy of the sub-objects in the ontology, and the copy is implemented layer by layer.

First read hereShallow copy. Cop1 creates an image for the current origin. Where the elements in origin point, and the elements in cop1 point. This is what the official doc says.inserts references into it to the objects found in the original.

The key here is,origin[2], That is, the list of [3, 4. AccordingShallow copyIncop1[2]It points to the same list [3, 4]. If we change this list, the origin and cop1 will change at the same time. That's whyorigin[2][0] = "hey!"Then, cop1 becomes[1, 2, ['hey!', 4]].

 

Let's take a look.Deep copy. It can be seen that cop2 stores each layer of origin in a copy. At this timeorigin[2]Andcop2[2]Although the values are equal to [3, 4], they are not the same list.

 

Since it is completely independent, no matter how you change one of them, the other will naturally not change.

 

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.