Skip to content

Python Deep Copy vs Shallow Copy Error Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about Python Deep Copy vs Shallow Copy Error Fix. We cover key concepts, practical examples, and best practices.

Modifying a copied list or dictionary in Python sometimes changes the original. This happens because copy() and assignment create shallow copies — nested objects are shared, not duplicated. Deep copying creates fully independent copies.

The Problem

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

copied[0] = 99
copied[1][0] = 88

print(f"Original: {original}")
print(f"Copied:   {copied}")

Output:

Original: [1, [88, 3], 4]  # Inner list was modified!
Copied:   [99, [88, 3], 4]

Wrong Code

# WRONG — shallow copy shares nested objects
def process_data(data):
    processed = data.copy()
    # Modifies nested dict in both processed AND original
    processed['config']['debug'] = True
    return processed

config = {'config': {'debug': False}}
result = process_data(config)
print(config['config']['debug'])  # True — original was modified

Right Code

import copy

def process_data(data):
    processed = copy.deepcopy(data)
    processed['config']['debug'] = True
    return processed

config = {'config': {'debug': False}}
result = process_data(config)
print(f"Original: {config['config']['debug']}")
print(f"Result:   {result['config']['debug']}")

Expected output:

Original: False
Result: True

Step-by-Step Fix

Step 1: Identify shallow vs deep copy behavior

# Shallow copy — one level deep
shallow = original.copy()

# Deep copy — fully recursive
deep = copy.deepcopy(original)

Step 2: Use deepcopy for nested structures

import copy

nested = {'data': [{'id': 1, 'tags': ['a', 'b']}]}
duplicate = copy.deepcopy(nested)
duplicate['data'][0]['tags'].append('c')

print(nested['data'][0]['tags'])      # ['a', 'b'] — unchanged
print(duplicate['data'][0]['tags'])     # ['a', 'b', 'c']

Step 3: Know which types need deepcopy

# Safe with shallow copy (immutable or simple)
numbers = [1, 2, 3]
safe_copy = numbers[:]

# Needs deep copy (nested mutables)
matrix = [[1, 2], [3, 4]]
safe_copy = [row[:] for row in matrix]  # Manual deep copy

Step 4: Handle custom objects

import copy

class Config:
    def __init__(self):
        self.data = {'key': [1, 2, 3]}

    def __copy__(self):
        return Config()

    def __deepcopy__(self, memo):
        new = Config()
        new.data = copy.deepcopy(self.data, memo)
        return new

Step 5: Verify independence

original = {'nested': {'value': 1}}
deep = copy.deepcopy(original)
deep['nested']['value'] = 2

assert original['nested']['value'] == 1

Prevention Tips

  • Use copy.deepcopy() for any nested mutable structure
  • Use list comprehensions [row[:] for row in matrix] for list of lists
  • Consider using immutable data structures (tuples, frozenset)
  • Document which functions modify input arguments vs returning copies
  • Test with assert to verify copy independence

Common Mistakes with deep copy

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between shallow copy and deep copy?

A shallow copy creates a new object but fills it with references to the same nested objects. A deep copy creates a completely independent copy with all nested objects recursively duplicated. Shallow copies share nested data; deep copies do not.

When should I use copy.copy vs copy.deepcopy?

Use copy.copy() for flat structures (lists of integers, single-level dicts). Use copy.deepcopy() for nested structures (lists of dicts, dicts of lists, custom objects with mutable attributes). Deep copy is slower but safer for complex structures.

How does assignment (=) differ from copy?

Assignment creates a new reference to the same object — there is only one object. Copy creates a new object with the same values. Deep copy creates a new object with recursively copied nested objects. Assignment and shallow copy both share nested data with the original.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro