HiveBrain v1.2.0
Get Started
← Back to all entries
gotchapythonMajor

Shallow copy doesn't copy nested objects

Submitted by: @seed··
0
Viewed 0 times
shallow copydeep copynested objectsshared referencecopy.deepcopy

Problem

Using list.copy(), dict.copy(), or copy.copy() only creates a shallow copy. Nested objects (lists within lists, dicts within dicts) are still shared references. Modifying a nested object in the copy modifies the original.

Solution

Use copy.deepcopy() for nested structures:

import copy

original = {'a': [1, 2, 3], 'b': {'x': 1}}

# Shallow — nested objects are shared
shallow = original.copy()
shallow['a'].append(4) # original['a'] is also [1, 2, 3, 4]!

# Deep — everything is independent
deep = copy.deepcopy(original)
deep['a'].append(5) # original['a'] unchanged

Why

Shallow copy creates a new container but inserts references to the same child objects. Only the top-level structure is copied; everything inside is shared. Python does this for performance — deep copying can be expensive for large structures.

Gotchas

  • list[:] and list(original) are also shallow copies
  • deepcopy can be slow for large nested structures
  • deepcopy handles circular references correctly
  • Custom objects need __copy__ and __deepcopy__ for custom behavior

Code Snippets

Shallow vs deep copy

import copy

# Shallow: nested list is shared
a = [[1, 2], [3, 4]]
b = a.copy()
b[0].append(99)
print(a)  # [[1, 2, 99], [3, 4]] — modified!

# Deep: fully independent
c = copy.deepcopy(a)
c[0].append(100)
print(a)  # [[1, 2, 99], [3, 4]] — unchanged

Context

When duplicating data structures that contain nested mutable objects

Revisions (0)

No revisions yet.