Python how to make a copy of the object

Learn how to copy an object in Python with an example. Deep and shallow copies explained, along with the copy module.

Making a Copy of an Object in Python

Learning how to make a copy of an object in Python is a useful skill to have in your programming toolbox. In this article, we will cover two ways of making a copy of an object: using the copy.copy() method and the copy.deepcopy() method.

copy.copy()

The copy.copy() method creates a shallow copy of an object. It takes the object to be copied as its only argument and returns the shallow copy. A shallow copy of an object is a new object that contains the same values as the original object. However, a shallow copy of a container object only copies the reference to the container, not the elements inside the container.


import copy

# original object 
original = [[1, 2, 3], [4, 5, 6]]

# shallow copy
shallow_copy = copy.copy(original)

# original and shallow copy are equal
print(original == shallow_copy)
# Output: True

# modifying the shallow copy
shallow_copy[0][1] = 20

# original and shallow copy are different
print(original == shallow_copy)
# Output: False

In the above example, original is a list of lists. We make a shallow copy of original and assign it to shallow_copy. Both original and shallow_copy have the same values. However, when we modify the shallow copy, the original object remains unchanged.

copy.deepcopy()

The copy.deepcopy() method creates a deep copy of an object. It takes the object to be copied as its only argument and returns the deep copy. A deep copy of an object is a new object that contains the same values as the original object. A deep copy of a container object also copies the elements inside the container.


import copy

# original object 
original = [[1, 2, 3], [4, 5, 6]]

# deep copy
deep_copy = copy.deepcopy(original)

# original and deep copy are equal
print(original == deep_copy)
# Output: True

# modifying the deep copy
deep_copy[0][1] = 20

# original and deep copy are different
print(original == deep_copy)
# Output: False

In the above example, original is a list of lists. We make a deep copy of original and assign it to deep_copy. Both original and deep_copy have the same values. However, when we modify the deep copy, the original object remains unchanged.

That's it! You now know how to make a copy of an object in Python using the copy.copy() method and the copy.deepcopy() method. Knowing how to make a copy of an object can be a useful skill to have when working with complex data structures.

Answers (0)