DEV Community

Cover image for Are You Really Copying in Python? ๐Ÿคฏ Shallow vs Deep Copy Explained
Chandrani Mukherjee
Chandrani Mukherjee

Posted on

Are You Really Copying in Python? ๐Ÿคฏ Shallow vs Deep Copy Explained

Understanding the difference between shallow copy and deep copy is key when working with mutable objects in Python like lists, dictionaries, or custom classes.


๐Ÿ“ฆ What is a Shallow Copy?

A shallow copy creates a new object, but inserts references to the original objects inside it.

โœ… Example:

import copy

original = [[1, 2], [3, 4]]
shallow = copy.copy(original)

shallow[0][0] = 99

print(original)  # [[99, 2], [3, 4]]
Enter fullscreen mode Exit fullscreen mode

๐ŸŽฏ Original is affected because inner objects are shared.


๐ŸŒŠ What is a Deep Copy?

A deep copy creates a new object and recursively copies all nested objects.

โœ… Example:

import copy

original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)

deep[0][0] = 99

print(original)  # [[1, 2], [3, 4]]
Enter fullscreen mode Exit fullscreen mode

โœ… Original is NOT affected because everything is duplicated.


๐Ÿ” Comparison Table

Feature Shallow Copy Deep Copy
New outer object? โœ… Yes โœ… Yes
New inner objects? โŒ No (shared) โœ… Yes (copied)
Uses copy.copy() โœ… โŒ
Uses copy.deepcopy() โŒ โœ…

๐Ÿงช When to Use Which?

  • Use shallow copy if:

    • Your object has only immutable or flat structure
    • You want faster performance
  • Use deep copy if:

    • Your object has nested mutable objects
    • You want full isolation

๐Ÿ“š Pro Tip

Custom classes may need a custom __deepcopy__() method if they hold external references or open files.


๐Ÿ”— Resources

Top comments (0)