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.
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’.
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.
copy - Shallow and deep copy operations - Python 3.9.0 documentation
Assignment statements in Python do not copy objects, they create bindings between a target and an object. For…