person using black laptop computer
Photo by freestocks on Unsplash

There are two methods that you can use to copy objects in Python, namely, copy() and deepcopy().

They are similar and can be confusing for a lot of people. There is however a subtle difference.

Here is the explanation from the docs:

-A shallow copy constructs a new compound object and then (to the extent possible) >-inserts references into it to the objects found in the original. -A deep copy constructs a new compound object and then, recursively, inserts copies >-into it of the objects found in the original.

Maybe, an even more comprehensive description can be found here:

-A shallow copy means constructing a new collection object and then populating it with >-references to the child objects found in the original. In essence, a shallow copy is >-only one level deep. The copying process does not recurse and therefore won’t create >-copies of the child objects themselves. -A deep copy makes the copying process recursive. It means first constructing a new >-collection object and then recursively populating it with copies of the child objects >-found in the original. Copying an object this way walks the whole object tree to >-create a fully independent clone of the original object and all of its children.

Here is an example of the copy():

 first_list = [[1, 2, 3], ['a', 'b', 'c']]
 ​
 second_list = first_list.copy()
 ​
 first_list[0][2] = 831
 ​
 print(first_list)  # [[1, 2, 831], ['a', 'b', 'c']]
 print(second_list)  # [[1, 2, 831], ['a', 'b', 'c']]

Here is an example of the deepcopy() case:

 import copy
 ​
 first_list = [[1, 2, 3], ['a', 'b', 'c']]
 ​
 second_list = copy.deepcopy(first_list)
 ​
 first_list[0][2] = 831
 ​
 print(first_list)  # [[1, 2, 831], ['a', 'b', 'c']]
 print(second_list)  # [[1, 2, 3], ['a', 'b', 'c']]

That’s pretty much it.

I hope you find this useful.