What are the uses and precautions of deep and shallow copying in Python?

王林
Release: 2023-05-31 08:05:35
forward
1804 people have browsed it

    1. Python Deep and Shallow Copy Concept

    In Python, when an assignment operation is performed, a reference to an object is actually assigned to a variable. , so these two variables point to the same object. If we need to copy an object, we need to use the copy operation.

    Shallow Copy refers to creating a new object and then copying the reference of the original object to the new object. Because the new object shares the same memory address as the original object, when the value of one object is modified, the value of the other object is also affected. A shallow copy only copies one layer of the object's contents.

    Recursively copy all the contents of the original object and its sub-objects to create a new object. This is Deep Copy. Because the new object does not share a memory address with the original object, they are completely independent, so changing the value of one object does not affect the value of the other object.

    2. Python deep and shallow copy usage scenarios

    Shallow copy is suitable for situations where the object hierarchy is shallow, such as the copying of simple objects such as lists, tuples, and dictionaries. If the elements of an object are all of immutable type, you can use shallow copy to copy the object.

    If the object hierarchy is complex, such as a list of nested lists or a dictionary of nested dictionaries, then deep copy is a suitable choice. If an object's elements contain mutable objects, a deep copy must be used when a copy is required.

    3. Notes on Python deep and shallow copies

    • For immutable objects (such as numbers, strings, tuples, etc.), shallow copies and deep copies are the same .

    • Shallow copy will only copy one level of content of mutable objects (such as lists and dictionaries), but will not recursively copy the sub-objects contained in mutable objects. If you need to recursively copy sub-objects, you must use deep copy.

    • When an object contains a circular reference, attempting a deep copy may cause infinite recursion, causing the program to crash. Therefore, you must be careful with objects containing circular references when using deep copies.

    • When using deep copy, if the hierarchical structure of the object is complex, it may cause performance problems, so deep copy must be used with caution.

    4. Python deep and shallow copy implementation

    Python provides two ways to implement deep and shallow copy: using the copy module and using the pickle module.

    1. Use the copy module

    The copy module in Python provides two functions, namely shallow copy and deep copy.

    Shallow copy can be implemented using the copy() function, for example:

    import copy
    
    a = [1, 2, 3]
    b = copy.copy(a)
    print(b)  # [1, 2, 3]
    Copy after login

    Deep copy can be implemented using the deepcopy() function, for example:

    import copy
    
    a = [[1, 2], [3, 4]]
    b = copy.deepcopy(a)
    print(b)  # [[1, 2], [3, 4]]
    Copy after login

    2. Use the pickle module

    The pickle module in Python can serialize Python objects into byte streams and deserialize byte streams into Python objects. Through the pickle module, deep copy can be achieved.

    Deep copy can be implemented using the pickle module, for example:

    import pickle
    
    a = [[1, 2], [3, 4]]
    b = pickle.loads(pickle.dumps(a))
    print(b)  # [[1, 2], [3, 4]]
    Copy after login

    It should be noted that using the pickle module to implement deep copy may cause performance problems, so you need to be careful when using it.

    5. Summary

    Deep and shallow copy in Python is a very practical concept. Mastering the usage scenarios and precautions of deep and shallow copy can help us better handle the copying and modification of objects. When implementing deep and shallow copy, we can use the copy module and pickle module in Python, and choose the appropriate method according to the specific situation. It should be noted that when using deep copy, if the object hierarchy is complex, it may cause performance problems, so deep copy must be used with caution. During the development process, we should try to use shallow copy as much as possible, and only consider using deep copy when necessary.

    In addition, when using deep copy, if the elements of the object contain mutable objects, you must be careful to handle objects containing circular references, otherwise you may fall into infinite recursion and cause the program to crash.

    In short, deep and shallow copy is a very important concept in Python. Mastering the usage and precautions of deep and shallow copy can help us better handle the copying and modification of objects, and improve the performance and maintainability of the program.

    Finally, let’s look at a practical example to demonstrate how to use deep and shallow copies.

    Suppose we have a complex object containing a list and dictionary, and we need to copy and modify it. The following is a sample code:

    import copy
    
    # 定义一个包含列表和字典的复杂对象
    a = {
        "name": "Tom",
        "age": 18,
        "scores": [80, 90, 95],
        "info": {
            "address": "Beijing",
            "phone": "1234567890"
        }
    }
    
    # 浅拷贝
    b = copy.copy(a)
    b["name"] = "Jerry"
    b["scores"].append(100)
    b["info"]["address"] = "Shanghai"
    print(a)  # {'name': 'Tom', 'age': 18, 'scores': [80, 90, 95, 100], 'info': {'address': 'Shanghai', 'phone': '1234567890'}}
    print(b)  # {'name': 'Jerry', 'age': 18, 'scores': [80, 90, 95, 100], 'info': {'address': 'Shanghai', 'phone': '1234567890'}}
    
    # 深拷贝
    c = copy.deepcopy(a)
    c["name"] = "Lucy"
    c["scores"].append(99)
    c["info"]["address"] = "Guangzhou"
    print(a)  # {'name': 'Tom', 'age': 18, 'scores': [80, 90, 95, 100], 'info': {'address': 'Shanghai', 'phone': '1234567890'}}
    print(c)  # {'name': 'Lucy', 'age': 18, 'scores': [80, 90, 95, 100, 99], 'info': {'address': 'Guangzhou', 'phone': '1234567890'}}
    Copy after login

    In the above sample code, we first define a complex object a containing a list and a dictionary, and then use shallow copy and deep copy to copy and modify it.

    By calling the copy() function to make a shallow copy of object a, you can obtain a new object b. Then, we modified the address attributes in the name, scores, and info of the new object b, and printed the values ​​of the original object a and the new object b. It can be seen that the value of the original object a has not changed, but the value of the new object b has changed.

    By using the deepcopy() function to deep copy object a, we can get a brand new object c. Then, we modified the address attributes in the name, scores, and info of the new object c, and printed the values ​​of the original object a and the new object c. It can be seen that the value of the original object a has not changed, but the value of the new object c has changed.

    Through the above sample code, we can see that deep and shallow copies are very useful when dealing with complex objects, and can help us better handle the copying and modification of objects. In actual development, we should choose an appropriate copy method according to specific scenarios, use shallow copies as much as possible, and only use deep copies when necessary.

    The above is the detailed content of What are the uses and precautions of deep and shallow copying in Python?. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template