Getting Started with Python day07-- copy depth

Copy depth

  • Direct assignment: in fact, the referenced object

    a = [1,2,3]
    b = a
    print(a, b) # [1,2,3] [1,2,3]
    print(id(a),id(b)) # 4497919088 4497919088
    a = 5
    print(a, b) # 5 5
    print(id(a),id(b)) # 4498367856 4498367856

    b = a: assignment references, a and b are the same object.

  • Shallow copy (copy): copy child objects inside the parent object, the object will not be copied.

a = {1:[1,2,3]}

b = a.copy()

a[2] = a.pop(1)

a[2].append(4)

print(a,b) # [2,[1, 2, 3, 4]], [1: [1, 2, 3, 4]]

b = a.copy (): shallow copy, a and b are a separate object, sub-object, or they point to a unified object (reference).

  • Deep copy (deepcopy): deepcopy method copy module, complete copy of the parent object and child objects.

Depth necessary to introduce the copy module copies:

import copy 

a = {1:[1,2,3]}

c = copy.deepcopy(a) 

a[2].append(5) 

print(a,c) # a, c ({2: [1, 2, 3, 5]}, {1: [1, 2, 4]})

Shallow copy:

Address and a copy of the original object out of the new object is not the same, but the address and the address of the original object in the variable element of the new object inside the variable elements (such as lists, dictionaries) are the same, that is to say shallow copy it is a shallow copy of a data structure (immutable elements), an object in the variable element and not copied to the new address to which a deep data structures, but the original object and point to the same elements in the variable an address, so the original object or a new object in the variable element of this when making changes, both objects are changed simultaneously.

Deep copy:

For immutable, (space saving, fight for change can not be made, it will have to open up a new memory space) with the original memory address.

For variable, to give the container opening up new address (the new container will have to distinguish between variable immutable type, if the variable will have to open up new containers memory space, if the type is immutable same shared memory address to obtain the original and so on).

Deep copy is to distinguish between the data type of the variable immutable; memory address for direct copying immutable data type; for variable data type, and then open a memory

Guess you like

Origin www.cnblogs.com/yding/p/12450901.html