春江暮客

春江暮客的个人学习分享网站

The difference between shallow copy and deepcopy in Python

2018-12-29 Technology
The difference between shallow copy and deepcopy in Python

In Python, copying objects is common, and a lot of “why did both variables change?” bugs come from mixing up three different operations: assignment, shallow copy, and deep copy.

“The difference between shadowcopy and deepcopy in python”

Among assignment (=), shallow copy (copy), and deep copy (deepcopy), the most confusing part is usually not assignment vs. copy, but whether a shallow copy still shares nested mutable objects.

Assignment does not copy an object. It only binds another variable name to the same object. Because of that, changes seen through one variable are still changes to the same underlying object.

A shallow copy duplicates the outer container, but nested mutable objects may still be shared. A deep copy recursively duplicates nested objects too, so it is usually more isolated.

A practical rule of thumb is:

  • Use assignment when you only want another name for the same object.
  • Use shallow copy when copying the outer container is enough.
  • Use deep copy when nested lists or dictionaries also need to be independent.

Below is a practical code example illustrating the differences among the three.

Code

    from copy import deepcopy
    dic1 = {'a': 2, 'b': 3, 'c': 4}
    dic2=dic1
    dic1["a"]=1
    print(dic1)
    #{'a': 1, 'b': 3, 'c': 4}
    print(dic2)
    #{'a': 1, 'b': 3, 'c': 4}
    # Assignment statement: both are exactly the same, changing one changes both
    dic1 = {'a': [1,2,3], 'b': 3, 'c': 4}
    dic2 = dic1.copy()
    dic1["a"] = [2,3,4]
    print(dic1)
    #{'a': [2, 3, 4], 'b': 3, 'c': 4}
    print(dic2)
    #{'a': [1, 2, 3], 'b': 3, 'c': 4}
    ### Changing the value does not affect the other object's value
    dic1 = {'a': [1,2,3], 'b': 3, 'c': 4}
    dic2 = dic1.copy()
    dic1["a"].append(4)
    print(dic1)
    #{'a': [1, 2, 3, 4], 'b': 3, 'c': 4}
    print(dic2)
    #{'a': [1, 2, 3, 4], 'b': 3, 'c': 4}
    ### This shows shallow copy copies elements and references to sub-objects. If the sub-object is mutable, changes affect both objects. See https://docs.python.org/3/library/copy.html for reference.
    dic1 = {'a': [1,2,3], 'b': 3, 'c': 4}
    dic2 = deepcopy(dic1)
    dic1["a"].append(4)
    print(dic1)
    #{'a': [1, 2, 3, 4], 'b': 3, 'c': 4}
    print(dic2)
    #{'a': [1, 2, 3], 'b': 3, 'c': 4}

Summary

In real code, assignment is usually not the right choice when you truly want “a copy,” because it only creates another reference.

If your data structure contains nested mutable objects and you want complete isolation, deepcopy is the safer choice. Just remember that it also costs more memory and time, so it should be used deliberately on large objects.

友情链接

其它