This is What You Need to Know About Copies - Python

When solving one of the many problems in Hacker Rank (which I love to do when I have time) I tried to isolate an array input to preserve its original value and modify the copy as I wanted. The code was not even compiling and then I realized when modifying the copy I was also modifying the original object. The truth, mates, was that I was dealing with a shallow copy of the object. And not knowing things and concepts hurts.

So, as usual, I decided to clarify this concept for me. And now I want to share it with you 🤓

What are Shallow and Deep copies

The difference between shallow and deep copies are only relevant for compound objects (objects that contain other objects, like lists, arrays, dictionaries, or class instances).

Shallow CopyDeep Copy
It creates a copy of the original object by inserting references to all the objects it contains (like for each array element). Hence, any change made in any of the objects (original and copy) will be brought to both because they are the same in memory (they have the same id)It creates a copy of the original object by copying all the objects it contains (no references). Hence, any change made in any of the objects (original and copy) will not be brought to the other one.

In Action

To demonstrate these behaviours, I will use the python module copy that has both methods: shallow and deep copy. When we type a = b we are actually using shallow copy. To make deep copies we have to use a = copy.deepcopy(b)

Shallow Copy

07_shallowCopy.pngShallow copy of object a

We see that when adding an element in the copy b, this element is also added to a.

Deep Copy

07_deepCopy.pngDeep copy of object a

We see that when modifying an element in the copy c, this element is not modified in a.

Ids

The ids indicate a unique identifier to objects that can be related to the memory allocation. Let's check the id of each object created.

07_ids.pngobjects' ids

We see that the id of a and b is the same as b is a shallow copy of a. On the other hand, c id is different from a as c is a deep copy of a, hence a hole new object.

Wrapping Up

Be careful when working with copies and be thoughtful about your decisions.

You would also want to avoid these headaches during coding tests when your code would not compile even when your thinking is in the right direction. I've been there haha


Thanks for reading 😊☕️
And this is also a post celebration for the new Hashnode! Proud to be part of this amazing community o/

No Comments Yet