Shallow copy and deep copy in Python

Shallow copy and deep copy in Python


Refer to "Python3 from entry to actual combat"

One, shallow copy

Shallow copy is similar to copying a webpage file. The new webpage file and the original webpage file are two different objects, but their content is the same

	import copy
    
    a = ['hello',[2,3,4]]#如果a是一个简单的值,a 和 b是一样的 
    b = copy.copy(a)
    print(a) 
    print(b)
    print(a is b) 
    print(id(a))
    print(id(b))
    #尽管a,b是不同的对象,但是两个对象对应元素的值是一样的,引用的是同一个对象.
    print(id(a[0]))
    print(id(b[0]))
    a[1] = 'xusong'
    print(b[1])#这样看起来好像并不会修改b
    
    '''
    ['hello', [2, 3, 4]]
    ['hello', [2, 3, 4]]
    False
    2776165785024#内存地址有可能不同,但是应该符合规则
    2776165775296
    2776165704944
    2776165704944
    [2, 3, 4]
    '''

Second, deep copy

Deep copy: Unlike shallow copy, deep copy will copy (copy) the nested object of this object, and copy the nested object of the nested object (shallow copy only performs the value of the element contained in the outermost object). copy)

	a = ['hello',3,[3,5,6]]
    b = a.copy()
    a[2][1] = 9
    print(b[2][1])#这样就可以修改,虽然他们的id还是不一样的(因为引用不同)
    print(id(a))
    print(id(b))
    print(id(a[0]))
    print(id(b[0]))
    '''
    运行结果如下:
    
     9
    2776165806336
    2776182493248
    2776165704944
    2776165704944   
    '''
	a = ['hello',3,[3,5,6]]
    b = a#这里直接改成=
    a[2][1] = 9
    print(b[2][1])#现在我们发现,他们连所有的内存地址都一样了
    print(id(a))
    print(id(b))
    print(id(a[0]))
    print(id(b[0]))
    '''
    运行结果如下:
    
     9
    2776165883328
    2776165883328
    2776165704944
    2776165704944
    '''

Guess you like

Origin blog.csdn.net/qq_45911278/article/details/112011236