What is the difference between shallow copy, deepcopy and normal assignment operation?

后端 未结 11 2208
温柔的废话
温柔的废话 2020-11-21 07:11
import copy

a = \"deepak\"
b = 1, 2, 3, 4
c = [1, 2, 3, 4]
d = {1: 10, 2: 20, 3: 30}

a1 = copy.copy(a)
b1 = copy.copy(b)
c1 = copy.copy(c)
d1 = copy.copy(d)


prin         


        
11条回答
  •  难免孤独
    2020-11-21 07:43

    Below code demonstrates the difference between assignment, shallow copy using the copy method, shallow copy using the (slice) [:] and the deepcopy. Below example uses nested lists there by making the differences more evident.

    from copy import deepcopy
    
    ########"List assignment (does not create a copy) ############
    l1 = [1,2,3, [4,5,6], [7,8,9]]
    l1_assigned = l1
    
    print(l1)
    print(l1_assigned)
    
    print(id(l1), id(l1_assigned))
    print(id(l1[3]), id(l1_assigned[3]))
    print(id(l1[3][0]), id(l1_assigned[3][0]))
    
    l1[3][0] = 100
    l1.pop(4)
    l1.remove(1)
    
    
    print(l1)
    print(l1_assigned)
    print("###################################")
    
    ########"List copy using copy method (shallow copy)############
    
    l2 = [1,2,3, [4,5,6], [7,8,9]]
    l2_copy = l2.copy()
    
    print(l2)
    print(l2_copy)
    
    print(id(l2), id(l2_copy))
    print(id(l2[3]), id(l2_copy[3]))
    print(id(l2[3][0]), id(l2_copy[3][0]))
    l2[3][0] = 100
    l2.pop(4)
    l2.remove(1)
    
    
    print(l2)
    print(l2_copy)
    
    print("###################################")
    
    ########"List copy using slice (shallow copy)############
    
    l3 = [1,2,3, [4,5,6], [7,8,9]]
    l3_slice = l3[:]
    
    print(l3)
    print(l3_slice)
    
    print(id(l3), id(l3_slice))
    print(id(l3[3]), id(l3_slice[3]))
    print(id(l3[3][0]), id(l3_slice[3][0]))
    
    l3[3][0] = 100
    l3.pop(4)
    l3.remove(1)
    
    
    print(l3)
    print(l3_slice)
    
    print("###################################")
    
    ########"List copy using deepcopy ############
    
    l4 = [1,2,3, [4,5,6], [7,8,9]]
    l4_deep = deepcopy(l4)
    
    print(l4)
    print(l4_deep)
    
    print(id(l4), id(l4_deep))
    print(id(l4[3]), id(l4_deep[3]))
    print(id(l4[3][0]), id(l4_deep[3][0]))
    
    l4[3][0] = 100
    l4.pop(4)
    l4.remove(1)
    
    print(l4)
    print(l4_deep)
    print("##########################")
    print(l4[2], id(l4[2]))
    print(l4_deep[3], id(l4_deep[3]))
    
    print(l4[2][0], id(l4[2][0]))
    print(l4_deep[3][0], id(l4_deep[3][0]))
    

提交回复
热议问题