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

后端 未结 11 2211
温柔的废话
温柔的废话 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:33

    >>lst=[1,2,3,4,5]
    
    >>a=lst
    
    >>b=lst[:]
    
    >>> b
    [1, 2, 3, 4, 5]
    
    >>> a
    [1, 2, 3, 4, 5]
    
    >>> lst is b
    False
    
    >>> lst is a
    True
    
    >>> id(lst)
    46263192
    
    >>> id(a)
    46263192 ------>  See here id of a and id of lst is same so its called deep copy and even boolean answer is true
    
    >>> id(b)
    46263512 ------>  See here id of b and id of lst is not same so its called shallow copy and even boolean answer is false although output looks same.
    

提交回复
热议问题