DevJunction

What is a Deep Copy and a Shallow Copy in Python ?

Let’s discuss Deep copy and Shallow copy in Python.

🌟 Deep Copy-
Let’s say you have created your resume on MS Word, and you send it over email to your friend for review.

He reviewed it and made some corrections.

But you said corrections are not reflected on my side.

What is going on here ? 🤷

Well this is what we call a deep copy or Pass by value.

Now take another example.

🌟 Shallow Copy-
Let’s say you have created your resume on Google Docs, and send a sharable link to your friend for review.

He made the corrections and voilà 🤘, corrections are also reflected on your side too. 🙋

This is what we call Shallow copy or pass by reference.

To understand how different kinds of copies works in Python, take a look at the code example below.

Shallow Copy

Keep in mind that shallow copy is about nested objects. It won't affect the even_nums if you made the changes in even_nums_copy’s first level elements.

Now what we can do if we really need a separate copy of a mutable(or list) object, no reference to the same memory block.

We can create a deep copy of it. To create a deep copy, we have ‘copy’ module in Python.

Let’s create a deep copy of ‘even_nums’.

Deep Copy

Now we have two separate lists, which are not referring to the same memory block. This is what we call a deep copy.

If you are working with Immutable objects, by default they create a deep copy, but with mutable objects, it can be a problem, because mutable objects don't create a deep copy by default.

So that is it for today, I hope you liked this article.

Reference:

Learning is a never ending process & We at DevJunction are making it more fun engaging & most importantly Free for all.