HomepythonThe copy Module in Python

The copy Module in Python

Introduction

The copy module in Python is used to create shallow and deep copies of objects. Copying is an essential operation when you need to duplicate objects while preserving the original object’s state. This module provides a simple interface for copying complex objects, including lists, dictionaries, and custom objects.

In this article, we will delve into the copy module, discussing its functions, differences between shallow and deep copies, and practical examples to demonstrate its usage.

Importing the copy Module

To use the copy module, you first need to import it into your Python script:

import copy

Shallow vs. Deep Copy

Before diving into the functions provided by the copy module, it’s crucial to understand the difference between shallow and deep copies.

Shallow Copy

A shallow copy creates a new object, but does not create copies of nested objects. Instead, it inserts references to the same objects present in the original. This means changes to nested objects in the copy will reflect in the original object.

Deep Copy

A deep copy creates a new object and recursively copies all nested objects, ensuring that no references to objects in the original are kept. Changes to nested objects in the copy do not affect the original object.

Functions in the copy Module

The copy module provides two primary functions: copy() and deepcopy().

copy.copy()

The copy() function returns a shallow copy of the object.

Syntax:

copy.copy(obj)
  • obj: The object to be copied.

Example:

import copy

# Original list
original_list = [1, 2, [3, 4]]

# Shallow copy
shallow_copy = copy.copy(original_list)

# Modifying the nested list in the shallow copy
shallow_copy[2][0] = 99

print("Original list:", original_list)
print("Shallow copy:", shallow_copy)

Output:

Original list: [1, 2, [99, 4]]
Shallow copy: [1, 2, [99, 4]]

As seen, modifying the nested list in the shallow copy affects the original list.

copy.deepcopy()

The deepcopy() function returns a deep copy of the object.

Syntax:

copy.deepcopy(obj)
  • obj: The object to be copied.

Example:

import copy

# Original list
original_list = [1, 2, [3, 4]]

# Deep copy
deep_copy = copy.deepcopy(original_list)

# Modifying the nested list in the deep copy
deep_copy[2][0] = 99

print("Original list:", original_list)
print("Deep copy:", deep_copy)

Output:

Original list: [1, 2, [3, 4]]
Deep copy: [1, 2, [99, 4]]

Modifying the nested list in the deep copy does not affect the original list, demonstrating that deepcopy() creates completely independent copies.

Practical Examples

Example 1: Copying a List of Dictionaries

Copying a list of dictionaries can demonstrate the differences between shallow and deep copies.

import copy

# Original list of dictionaries
original_list = [{'a': 1}, {'b': 2}]

# Shallow copy
shallow_copy = copy.copy(original_list)

# Deep copy
deep_copy = copy.deepcopy(original_list)

# Modifying a dictionary in the shallow copy
shallow_copy[0]['a'] = 99

# Modifying a dictionary in the deep copy
deep_copy[1]['b'] = 100

print("Original list:", original_list)
print("Shallow copy:", shallow_copy)
print("Deep copy:", deep_copy)

Output:

Original list: [{'a': 99}, {'b': 2}]
Shallow copy: [{'a': 99}, {'b': 2}]
Deep copy: [{'a': 1}, {'b': 100}]

Changes in the shallow copy affect the original list, while changes in the deep copy do not.

Example 2: Copying Custom Objects

Copying custom objects can be useful when working with instances of user-defined classes.

import copy

class MyClass:
    def __init__(self, value):
        self.value = value

# Original object
original_obj = MyClass([1, 2, 3])

# Shallow copy
shallow_copy = copy.copy(original_obj)

# Deep copy
deep_copy = copy.deepcopy(original_obj)

# Modifying the list in the shallow copy
shallow_copy.value[0] = 99

# Modifying the list in the deep copy
deep_copy.value[1] = 100

print("Original object:", original_obj.value)
print("Shallow copy:", shallow_copy.value)
print("Deep copy:", deep_copy.value)

Output:

Original object: [99, 2, 3]
Shallow copy: [99, 2, 3]
Deep copy: [1, 100, 3]

Again, changes in the shallow copy affect the original object, while changes in the deep copy do not.

Tips and Best Practices

  1. Know When to Use Each: Use copy() for shallow copies when the object does not contain nested structures that you intend to modify. Use deepcopy() when you need a completely independent copy of an object with nested structures.
  2. Customizing Copy Behavior: For custom classes, you can define __copy__() and __deepcopy__() methods to control the copying behavior.
  3. Performance Considerations: Deep copying can be more computationally expensive than shallow copying due to the recursive copying of all nested objects. Use deep copies judiciously in performance-critical applications.

The copy module in Python is an essential tool for creating shallow and deep copies of objects. Understanding the differences between these types of copies and knowing when to use each can help you manage object duplication effectively in your programs. Whether you’re working with lists, dictionaries, or custom objects, the copy module provides a straightforward and reliable way to duplicate objects while preserving their state.

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular