Differences between shallow copy and deep copy in python

    Shallow copy
    • Shallow copy shares child object references between copies
    • can be created without importing copy module
    • constructs a new compound object and then inserts references into it to the objects found in the original.
    • changes in the nested objects of compound objects copied using shallow copy will be reflected in other copies
    • uses memory efficiently and hence faster
    Deep copy
    • Deep copy doesn't share child object references between copies
    • cannot be created without importing copy module
    • constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
    • changes in the nested objects of compound objects copied using deep copy will not be reflected in other copies
    • doesn't use memory efficiently and hence slower
    Shallow copy shares child object references between copies while Deep copy doesn't share child object references between copies.
    Deep copy creates a new object and then recursively populates it with copies of all objects including the child objects (nested objects) found in the original. So, deep copy creates a clone at a different memory location, so the original and the clone are two separate, independent objects and any changes made to one have no effect on the other.
    Shallow copy creates a new object and then populates it with references to the child objects (nested objects) found in the original. So, child objects in the original are not copied, just their references are copied. So, any changes to the child objects in the original will reflect in the copy and any changes to the child objects in the copy will reflect in the original. Therefore, the copy is not fully independent of the original
    If the original do not have any nested objects, shallow copy is the same as deep copy. For e.g., If a list has all immutable objects (int, float, str etc) then deep copy and shallow copy are same.
    Deep Copy is necessary when the original objects should not be modified. Deep copy is especially important in multithreading and multi-core programming, where separate parts of a program could attempt to modify the data at the same time, possibly corrupting it. So, having two independent copies is necessary in such situations.
    Shallow copy can be created in many ways:

    new_list = original_list[:]

    new_list = original_list + [ ]

    new_list = list(original_list)

    new_list = original_list * 1

    new_list = [i for i in original_list]

    import copy
    new_list = copy.copy(original_list)

    Deep capy can only be done using deepcopy ( ) method of copy module

    import copy
    new_list = copy.deepcopy(original_list)


difference-between-shallow-copy-deep-copy
gk