Categories
Python Answers

How to create a copy of an object in Python?

Spread the love

Sometimes, we want to create a copy of an object in Python.

In this article, we’ll look at how to create a copy of an object in Python.

How to create a copy of an object in Python?

To create a copy of an object in Python, we can use the copy.copy method to create a shallow copy of an object.

We can use copy.deepcopy to create a deep copy of an object.

For instance, we write

import copy

class C():
    def __init__(self):
        self.x = [1]
        self.y = [2]

c = C()
d = copy.copy(c)

to create a shallow copy of object c and assign it to d.

Likewise, we write

d = copy.deepcopy(c)

to create a deep copy of object c and assign it to d.

Conclusion

To create a copy of an object in Python, we can use the copy.copy method to create a shallow copy of an object.

We can use copy.deepcopy to create a deep copy of an object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *