How to Copy Objects in Python?

Estimated read time 2 min read

In Python, there are two main approaches to copy an object: shallow copy and deep copy.

A shallow copy creates a new object with a new memory address, but the contents of the object still refer to the original object. In other words, any changes made to the original object will be reflected in the shallow copy. Shallow copies can be made using the slicing operator [:], the built-in list() or dict() function, or the copy() method of certain objects.

A deep copy, on the other hand, creates a new object with a new memory address and all the contents of the original object are copied recursively. This means that changes made to the original object will not be reflected in the deep copy. Deep copies can be made using the deepcopy() method of the copy module.

Here are some examples:

Shallow Copy Examples

# Using slicing operator
original_list = [1, 2, 3]
shallow_copy = original_list[:]
original_list[0] = 10
print(shallow_copy)  # Output: [1, 2, 3]

# Using list() function
original_list = [1, 2, 3]
shallow_copy = list(original_list)
original_list[0] = 10
print(shallow_copy)  # Output: [1, 2, 3]

# Using copy() method
import copy

original_list = [1, 2, 3]
shallow_copy = original_list.copy()
original_list[0] = 10
print(shallow_copy)  # Output: [1, 2, 3]

Deep Copy Example

import copy

original_list = [1, [2, 3], 4]
deep_copy = copy.deepcopy(original_list)
original_list[1][0] = 10
print(deep_copy)  # Output: [1, [2, 3], 4]

Note that in the deep copy example, even though we changed the first element of the nested list in the original object, the deep copy was not affected.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply