Deep and Shallow copy in Python:

In case of Python, assignment statements do not copy but create a binding between a target and an object. In case we use = operator, the user thinks that it creates a new object, but it is not so. Only a new variable is created, which shares the reference of the original object. In some cases, a user wants to work with mutable objects in python for data science. To do this, the user looks for a way to create real copies or clones of these objects. The user sometimes wants copies that the user can modify without automatically modifying the original at the same time.

Sometimes we need a copy so that one can change the copy without changing the original one. Python has two methods for creation of copies:

  • Deep copy
  • Shallow copy

The module copy is there to make copies. Both deep and shallow copy can be performed using copy module.

Deep and Shallow copy in Python for Data Science - PST Analytics

In the code given above the copy() returns a shallow copy of list and deepcopy() returns deep copy of list.

Now we will look into the deep copy in detail.

Deep Copy:

Deep and Shallow copy in Python for Data Science - PST Analytics

In case of deep copy, the copying process occurs recursively. It simply means that first of all constructing a new collection object and after that, recursively populating it with copies of child objects which is found in the original. In the process of deep copy, a copy of an object is copy into another object. This means any changes which are made to a copy of object do not reflect in the original object.

Deep and Shallow copy in Python for Data Science - PST Analytics

Shallow copy:

A shallow copy constructs a new collection object and then populates it with references to the child objects found in the original. The process of copying is not recurs so; it won’t create copies of child objects themselves. When we use shallow copy, a reference object is copy into another object. This means any changes made to a copy of object reflects in the original object. We use the copy() function to implement this function.

Important Points to remember:

Difference between shallow and deep copying is relevant for compound objects.

  • In shallow copy construction of a new compound, object is done and then inserts a reference into it to objects found in the original.
  • In case of deep copy process, it constructs a new compound object and later recursively inserts copies into it the objects which are found in the original.

To learn more about it in python for data science, you can check this and this as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.