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

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

    Deep copy is related to nested structures. If you have list of lists, then deepcopy copies the nested lists also, so it is a recursive copy. With just copy, you have a new outer list, but inner lists are references. Assignment does not copy. For Ex

    import copy
    spam = [[0, 1, 2, 3], 4, 5]
    cheese = copy.copy(spam)
    cheese.append(3)
    cheese[0].append(3)
    print(spam)
    print(cheese)
    

    OutPut

    [[0, 1, 2, 3, 3], 4, 5] [[0, 1, 2, 3, 3], 4, 5, 3] Copy method copy content of outer list to new list but inner list is still same for both list so if you make changes in inner list of any lists it will affects both list.

    But if you use Deep copy then it will create new instance for inner list too.

    import copy
    spam = [[0, 1, 2, 3], 4, 5]
    cheese = copy.deepcopy(spam)
    cheese.append(3)
    cheese[0].append(3)
    print(spam)
    print(cheese)
    

    Output

    [0, 1, 2, 3] [[0, 1, 2, 3, 3], 4, 5, 3]

提交回复
热议问题