Open In App

Copy Module - Python

Last Updated : 12 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

copy module in Python provides essential functions for duplicating objects. It allows developers to create both shallow and deep copies of objects ensuring that modifications to the copy do not inadvertently affect the original object (or vice versa). This functionality is particularly useful when working with complex data structures like lists, dictionaries and custom objects that contain nested or mutable elements.

How to Import the copy Module

To use the copy module, you have toi first import it in your Python script by the following command:

import copy

Syntax and Functions

1. copy.copy(obj) (Shallow Copy)

Syntax:

copy.copy(obj)

  • Parameters: obj: object to be copied.
  • Returns: shallow copy of obj, where only the outer object is duplicated, while nested objects remain referenced.

2. copy.deepcopy(obj) (Deep Copy)

Syntax:

copy.deepcopy(obj)

  • Parameters: obj: object to be copied.
  • Returns: deep copy of obj, where all nested objects are also duplicated recursively.

Shallow Copy with copy.copy()

A shallow copy creates a new compound object but the elements contained within are references to the same objects found in the original. This means that for nested objects, changes in the copied object may reflect in the original.

Python
import copy

# original
a = [1, 2, [3, 4]]
# shallow copied
b = copy.copy(a)

# Modify a nested element in the shallow copy
b[2][0] = 'Changed'

print("Original:", a)
print("Shallow Copy:", b)

Output
Original: [1, 2, ['Changed', 4]]
Shallow Copy: [1, 2, ['Changed', 4]]

Explanation: nested list [3, 4] was not duplicated but referenced, so modifying it in the copy also changes it in the original.

Deep Copy with copy.deepcopy()

A deep copy creates a new object and recursively copies all nested objects found within the original. This results in an entirely independent object with no shared references.

Python
import copy

a = [1, 2, [3, 4]]
# deep copied
b = copy.deepcopy(a)

# Modify a nested element in the deep copy
b[2][0] = 'Changed'

print("Original:", a)
print("Deep Copy:", b)

Output
Original: [1, 2, [3, 4]]
Deep Copy: [1, 2, ['Changed', 4]]

Explanation: nested list is fully duplicated. Changes made in the deep copy do not affect the original list.

When to Use Shallow vs. Deep Copy

Use a Shallow Copy When:

  • The object contains only immutable elements.
  • Nested objects will remain unchanged.
  • A faster and more memory-efficient approach is needed.
  • Only the outer container should be duplicated, while inner elements remain referenced.

Use a Deep Copy When:

  • The object has mutable nested elements that need full independence.
  • Changes to the copied object should not affect the original.
  • A complete duplication of all nested objects is required.

Next Article
Article Tags :
Practice Tags :

Similar Reads