Image for post
Image for post

There is two types of copying objects in Python: deep and shallow. Here I will show how to perform both of them using built-in module copy.

Import module copy in your code

Try shallow copy

Let’s see how it works on deeply nested lists

Change of element a[2][0] leading to change in corresponding element b[2][0] as all nested lists in a are passed as reference on default.

Now let’s try deep copying:

We can see that when changing element with index [2][0] in a corresponding element in b is not changing as all nested lists in a are copied to b (nor passed by reference).

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store