Python Copy With Examples

Today we will learn about Python copy class. We will also learn about shallow copy, deep copy and and why do we need these different copy operations.

Python Copy

Python library provides us a Copy class with two operations – copy(x) and deepcopy(x) – for shallow copy and deep copy respectively. But why do we need them? Why can’t simple assignment of one object to another using equals operator is good enough?

The reason is that when we use equals python operator to create a new object, it actually creates a reference to the same object in the memory. Since both the variables refer to same object, any change in one will be reflected in other too. Most of the times we don’t want that, hence the need of a separate copy operation. Let’s prove our theory about assignment operator through a simple example.

Output of above python program is:

Notice that we didn’t changed old_list but since both the lists were pointing to same object, any change in one of them got reflected in other too.

Also if we have an immutable object then assignment operator is good enough as the object value will not change.

Shallow Copy

When we use python shallow copy function copy(), it actually creates a new object and then insert references of the objects found in the original object. So shallow copy is good enough in above case where we have a list of integers because the list elements are immutable. But it’s not good enough when we have a list of list. We will look into deep copy later, let’s first look at the python shallow copy example.

As you can see in above output that the change in new_list didn’t affected the old_list because we use copy function to copy the list.

Now let’s see an example where shallow copy operation will fail because it doesn’t copy elements in the original object recursively.

Output of above python copy example is:

The output clearly suggests that we need a separate operation for deep copy of objects.

Python Deep Copy

We should always use deepcopy(x) function with objects like list of lists, so that objects are copied recursively. Let’s change the above shallow copy example and use deep copy function and check the output. I have also added some more append and remove operations to the program.

Below image shows the output of python deep copy operation.

Python Copy

Note that this method is slower than shallow copy for obvious reasons, so use it only when it’s really required. Also deep copy will take more memory if the objects inside are also copied, so use it wisely and only if truly required.

That’s all about python copy and python deep copy operations.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: