How will you differentiate between shallow copy and deep copy in Python?

In Python there are two types of copy, namely, shallow copy and deep copy. This article explains the difference between them.

Shallow Copy

A shallow copy means constructing a new collection object and then populating it with references to the child objects found in the original.

The copying process is not recursive so that copies of the child objects is not created.

In the case of shallow copy a reference of object is copied into other object i.e any changes made to a copy do reflect in the original object.

In Python shallow copy can be implemented by using copy() function.

Here is the illustration of shallow copy.

Shallow Copy
Figure: Shallow Copy

Deep Copy

A deep copy means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original.

The copying process is recursive, hence copies of child copies is created, it means changes made to a copy of object do not reflect in the original object.

In python deep copy can be implemented using deepcopy() function.

Deep Copy
Figure: Deep Copy
Hence, a shallow copy constructs a new compound object and then inserts references into it to the objects found in original but deep copy constucts a new compound object and then, recursively , inserts copies into it of the objects found in the original.