How can I create a copy of an object in Python?

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

In Python, you can create a copy of an object using either shallow copy or deep copy depending on the level of duplication you need. Here's how you can achieve both:

1. Shallow Copy

A shallow copy creates a new object, but it only copies references to the objects contained within. If the original object contains mutable objects (e.g., lists, dictionaries), changes to those mutable objects in the original will be reflected in the copy.

Using the copy Module:

import copy original = [1, 2, [3, 4]] shallow_copy = copy.copy(original) # Modify the nested list in the original original[2][0] = 99 print(original) # Output: [1, 2, [99, 4]] print(shallow_copy) # Output: [1, 2, [99, 4]] (nested objects are shared)

Using Slicing (for Lists):

original = [1, 2, 3] shallow_copy = original[:] print(shallow_copy) # Output: [1, 2, 3]

2. Deep Copy

A deep copy creates a new object and recursively copies all objects within it. This ensures that changes to the original object do not affect the copy, even for nested mutable objects.

Using the copy Module:

import copy original = [1, 2, [3, 4]] deep_copy = copy.deepcopy(original) # Modify the nested list in the original original[2][0] = 99 print(original) # Output: [1, 2, [99, 4]] print(deep_copy) # Output: [1, 2, [3, 4]] (nested objects are independent)

3. Custom Copy Logic

For custom objects, implement the __copy__ and __deepcopy__ methods in your class.

Example:

import copy class MyClass: def __init__(self, value): self.value = value def __copy__(self): return MyClass(self.value) def __deepcopy__(self, memo): return MyClass(copy.deepcopy(self.value, memo)) # Create an object and copy it obj = MyClass([1, 2, 3]) shallow_copy = copy.copy(obj) deep_copy = copy.deepcopy(obj) obj.value[0] = 99 print(obj.value) # Output: [99, 2, 3] print(shallow_copy.value) # Output: [99, 2, 3] print(deep_copy.value) # Output: [1, 2, 3]

4. Using the copy Method for Built-in Types

Some built-in types, like dictionaries, provide their own copy method to create a shallow copy.

Example with Dictionary:

original = {"a": 1, "b": [2, 3]} shallow_copy = original.copy() original["b"][0] = 99 print(original) # Output: {'a': 1, 'b': [99, 3]} print(shallow_copy) # Output: {'a': 1, 'b': [99, 3]}

Summary

  • Shallow Copy: Use copy.copy() or slicing for lists. References to nested objects are shared.
  • Deep Copy: Use copy.deepcopy() to recursively copy all objects, ensuring independence from the original.
  • Custom Classes: Implement __copy__ and __deepcopy__ methods for fine-grained control.

Select shallow or deep copy based on whether you need independence for nested mutable objects. For in-depth Python coding techniques, check out Grokking Python Fundamentals on DesignGurus.io!

TAGS
Coding Interview
CONTRIBUTOR
Design Gurus Team

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
What is the difference between Availability and Reliability?
What are the key skills of a software engineer?
Describe the value of ux design?
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
Grokking Advanced Coding Patterns for Interviews
Master advanced coding patterns for interviews: Unlock the key to acing MAANG-level coding questions.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2024 Designgurus, Inc. All rights reserved.