Python shallow copy of the deep copy (variable immutable object)

The first problem encountered in deep and shallow copy is a copy of the assignment list with python in a for loop, the statement is used

a = b

This will continue into the b cycle, each calculated, and finally found a mess of the list, only to discover later, python in a = b does not create a a, b with the value assigned to it, but a copy of the address of b .

In fact, later in C #, another problem is also similar error, of course, the issue is much more complex, and therefore a specially rewritten.

I can not help but wonder, what is the difference between deep and shallow copy copy is, under what scenario to use shallow copy, and under what scenario with a deep copy of it?

1, first of all understand what is the deep and shallow copy copy

  • Mutable object, immutable objects

  In understanding the depth of copies, and to understand the variable immutable objects.

  Refers to the variable object is a variable value target address pointed to by the address that is opposite to immutable objects pointed objects are immutable. for example

  a = 5
  a = 6

  Here assigned a value twice, but the second time assignment, not a change of address, the difference is that after the statement is executed, the value of a point from the 5 local storage into a 6. Accordingly, a is a variable object.

  Well, here's '5' it? 5 is a number, when you enter the place 5:00 in the statement, it necessarily represent the number 5 is located, you can not re-assigned to the 5, so 5 is an immutable object. When you try to change when an immutable object, which in fact became a newborn object and return to you. For example, y = y + 1, returns the original y is not in fact the address of y.

  Immutable objects comprising: int, float, complex, long, str, unicode, tuple.

  • Copy of statement shades
Import Copy 
A = [1,2,3,4,5, [ ' A ' , ' B ' ]]
 # original object 
B = A # assignment, transfer reference object 
C = copy.copy (A) # copy of the object, shallow copy 
D = copy.deepcopy (A) # copy of the object, a deep copy 
Print  " A = " , A, "     ID (A) = " , ID (A), " ID (A [. 5]) = " , ID ( A [. 5 ])
 Print  " B = " , B, "     ID (B) = " , ID (B), " ID (B [. 5]) = ",id(b[5])
 Print  " C = " , C, "     ID (C) = " , ID (C), " ID (C [. 5]) = " , ID (C [. 5 ])
 Print  " D = " , D, "     ID (D) = " , ID (D), " ID (D [. 5]) = " , ID (D [. 5 ])
 Print  " * " * 70 

a.append ( . 6) # modify the object A 
A [. 5] .append ( ' C ' ) # modify objects in a [ 'a', 'b' ] array objects 
Print  "a=",a,"    id(a)=",id(a),"id(a[5])=",id(a[5])
print "b=",b,"    id(b)=",id(b),"id(b[5])=",id(b[5])
print "c=",c,"       id(c)=",id(c),"id(c[5])=",id(c[5])
print "d=",d,"            id(d)=",id(d),"id(d[5])=",id(d[5])

 

 

 assignment is a = b, but a copy address, the address is a reference to two.

copy function is separate from an address, storing the new object, but only recopy the variable objects, the address of immutable objects and constant, so if you change an immutable object, copy the object still change.

deepcopy is completely generate a new object, all the objects in the source object generates a new address on.

 

2. Why should copy depth

In fact, I have been using the relevant knowledge, but do not know who has been, not to think carefully about. For example, in a leetcode in question:

# 21. merge two ordered list 
# two ordered lists into a new sorted list and return. The new list is by all nodes in a given mosaic composed of two lists. 
class Solution (Object):
     DEF mergeTwoLists (Self, L1, L2):
         "" " 
        : of the type L1: ListNode 
        : of the type L2: ListNode 
        : rtype: ListNode 
        " "" 
        the p- = ListNode (0)
         ANS = the p-
 the while (L1 or L2 ):
             IF (L1 == None): 
                p.next = L2
                 return ans.next
             elif (L2 == None):       
                p.next = l1
                return ans.next
            else:
                if(l1.val>l2.val):
                    p.next = l2
                    p = p.next
                    l2 = l2.next
                else:
                    p.next = l1
                    p = p.next
                    l1 = l1.next
        return ans.next

Standard yellow line, is the position p nodes by ans recording, so p can be iterative, the final return ans, i.e., returned to the head pointer, here, it is readily understood that, ans = p operation is used ans copied p address not copy the value of p, p is not the point, but rather, p address where the execution will refer to ans. This is a shallow copy.

  • a = b b assignment statement typically used to record the address, if b is required in subsequent iterations, a may record the initial position.
  • shallow copy copy function, and modifications may operate some elements in the new object, while those commonly used in the original immutable objects or elements, at least the following benefits such
  1. Time, memory overhead smaller, more efficient the
  2. Analogy with programming ideas, immutable objects can be considered similar to a global variable, the variable is an instance of an object can be considered an object in a local variable, the benefits of doing so on the obvious
  • deepcopy is a completely new generation of an object, in which all objects are new, the source object does not matter, you can freely change.

3, the reference transfer function in relation

We often an object passed to the function, the function is also often the object operate. Although there are different assignment, but actually meaning between different operations is not the same.

def func1(nums):
    nums = set(nums)

def func2(nums):
    nums = [1,2,3,4,5]
l = [1,1,1,1]
func1(l)
func2(l)

In this operation, the function defined in nums been assigned to, but if you will find practical operation, in function nums is changed, but the function is ended, l, or equal [1,1,1,1 ].

This is because in the function, this object represents nums l of reference only, nums = set (nums) This statement is generated a SET (nums) objects, and the object address assigned to the nums this reference. And did not set (nums) content overwrite the contents of the address of nums is located.

 

def func3(nums):
    for i in range(len(nums)):
            nums[i] = 9

def func4(nums):
    nums.pop(1)
   nums.append(3)
l = [1,1,1,1] func3(l) func4(l)

In this operation, you will find the value of l has been transformed. This is because the operation is over whether the assignment for the index or list operations are performed for nums this variable points list object that is actually in operation on the address, changing the elements. This is actually python function parameter passing problem. There are a blog post written very clearly: Python function parameter passing: by value or reference .

So to remember, passing the address of the function in python that object. When the operator operates on the object address referred to, will change, or when you try to pass this parameter assignment, it will fail.

Guess you like

Origin www.cnblogs.com/masonmei/p/11618907.html