What is deep copy in python?

Nikhil Pandey
2 min readMay 14, 2023

--

⭐Deep copy in Python is the process of creating a new object that is a copy of an existing object, including all of its sub objects. This is in contrast to a shallow copy, which creates a new object that only contains references to the sub objects of the original object.

⭐Deep copies are often used when you need to make changes to an object without affecting the original object. For example, if you have a list of objects, you might want to make a deep copy of the list so that you can modify the copy without affecting the original list.

⭐There are several ways to create deep copies in Python. One way is to use the copy.deepcopy() function. For example, the following code creates a deep copy of a list:

>>> from copy import deepcopy
>>> list1 = [1, 2, 3]
>>> list2 = deepcopy(list1)
>>> list1[0] = 10
>>> list2
[1, 2, 3]

⭐As you can see, changing the value of the first element of list1 does not affect the value of the first element of list2. This is because list2 is a deep copy of list1.

⭐Another way to create deep copies in Python is to use the __copy__() and __deepcopy__() methods. These methods are called automatically when you use the copy() or deepcopy() functions. For example, the following code creates a deep copy of a class instance:

>>> class Foo:
… def __init__(self, value):
… self.value = value
… def __repr__(self):
… return "Foo(%r)" % self.value

>>> foo1 = Foo(10)
>>> foo2 = copy.deepcopy(foo1)
>>> foo1.value = 20
>>> foo2
Foo(10)

⭐As you can see, changing the value of the value attribute of foo1 does not affect the value of the value attribute of foo2. This is because foo2 is a deep copy of foo1.

⭐Deep copies are a powerful tool that can be used to protect your data from accidental changes. If you are working with objects that contain other objects, it is always a good idea to use deep copies instead of shallow copies.

That’ll for today! Bye (please mail me if your find anything to be improved. pandeynikhilone@gmail.com)or Have any suggestion! fill form

--

--

Nikhil Pandey

I am a student and a programming nerd. I learn and teach topics to help my fellow readers understand and apply their programming knowledge fluently.