Skip to content

Python copy vs deepcopy: Shallow and Deep Copying

  • The difference between a shallow copy and a deep copy, and why it matters.
  • How to make a shallow copy with copy.copy, slicing, and .copy() methods.
  • How copy.deepcopy recursively copies nested objects so they are independent.
  • The mutable default argument bug, and how default factories fix it.
  • When deep copy is necessary and when it is a costly mistake.
  • How to customize copying with __copy__ and __deepcopy__.

The copy module offers two operations: copy.copy makes a shallow copy that shares nested objects, and copy.deepcopy makes a deep copy that recursively copies them. The distinction only matters when an object contains other mutable objects. A shallow copy is fast and correct when you want a new container whose elements you will replace but not mutate; a deep copy is correct when you need a fully independent duplicate. The same sharing that makes a shallow copy cheap is the mechanism behind the classic mutable default argument bug. The module has been standard since Python’s early days.

When you copy a list of lists, “copy the container” and “copy everything in it” are different operations. A naive copy gives you a new outer list that still points at the same inner lists, so editing one copy’s inner list changes the other. The bug is silent: the outer lists are separate, but their contents are shared.

Shallow surprise:

matrix = [[1, 2], [3, 4]]
shallow = matrix.copy() # new outer list, same inner lists
shallow[0][0] = 99
print(matrix)
# [[99, 2], [3, 4]] <- the original changed too

The original matrix changed because shallow[0] is the same list object as matrix[0]. A shallow copy duplicated the outer list but reused the inner ones.

A shallow copy creates a new container and fills it with references to the same elements. copy.copy works on any object that supports copying, and built-in containers offer shortcuts: list[:] or list.copy(), dict.copy(), and set.copy().

import copy
orders = [1023, 1024, 1025]
shallow = copy.copy(orders)
shallow.append(1026)
print(orders, shallow)
# [1023, 1024, 1025] [1023, 1024, 1025, 1026] <- originals are separate
# slicing and .copy() do the same thing for built-ins
by_slice = orders[:]
by_method = orders.copy()
print(shallow is by_slice, by_slice is by_method)
# False False <- each is a distinct new list

Because the elements are plain ints, which are immutable, sharing is harmless: no one can mutate an int. A shallow copy is all you need when the elements are immutable or you only replace them rather than mutate them in place.

A deep copy recursively copies every object the structure reaches, so no object is shared between the copy and the original. copy.deepcopy is the operation; it follows references, handles cycles, and copies through nested containers.

import copy
matrix = [[1, 2], [3, 4]]
deep = copy.deepcopy(matrix)
deep[0][0] = 99
print(matrix)
# [[1, 2], [3, 4]] <- the original is untouched
print(deep)
# [[99, 2], [3, 4]]

The deep copy’s inner lists are new objects, so mutating one copy never reaches the other. This is the copy you want when you will modify nested structures and need the copies to be independent.

The same sharing that distinguishes shallow from deep underlies the most famous Python gotcha. A default argument value is evaluated once when the function is defined, not on each call, so a mutable default is shared across every call that uses it.

def add_order(order_id, seen=None):
if seen is None:
seen = []
seen.append(order_id)
return seen
print(add_order(1023)) # [1023]
print(add_order(1024)) # [1024] <- no leakage

If the default were seen=[], every call would append to the same list, and the second call would return [1023, 1024]. The None sentinel with a fresh list per call avoids the shared state. This is a shallow-copy issue in spirit: the default list is shared, just like the inner lists in a shallow copy.

Customizing with __copy__ and __deepcopy__

Section titled “Customizing with __copy__ and __deepcopy__”

A class can control how it is copied by defining __copy__ for shallow copies and __deepcopy__ for deep copies. __deepcopy__ receives a memo dict, which maps already-copied objects to their copies so cycles are handled.

import copy
class Order:
def __init__(self, order_id, tags):
self.order_id = order_id
self.tags = tags
def __copy__(self):
# shallow: new order, shared tags list
return Order(self.order_id, self.tags)
def __deepcopy__(self, memo):
# deep: new order, new tags list
return Order(self.order_id, copy.deepcopy(self.tags, memo))
original = Order(1023, ["rush", "fragile"])
shallow = copy.copy(original)
deep = copy.deepcopy(original)
shallow.tags.append("shared")
print(original.tags)
# ['rush', 'fragile', 'shared'] <- shallow copy shared the list
print(deep.tags)
# ['rush', 'fragile'] <- deep copy's list is independent

The shallow copy’s tags is the same list as the original’s, so the append leaks back. The deep copy’s tags is a new list, so it stays clean. Customizing lets a class pick the right semantics for its fields.

OrdersPortal caches a customer’s default shipping configuration and must give each order its own copy so editing one order’s address does not rewrite the customer’s default.

import copy
default_config = {
"customer": "Acme",
"address": {"street": "1 Main", "city": "Springfield"},
"tags": ["standard"],
}
# shallow copy shares the nested address dict and tags list
shallow = copy.copy(default_config)
shallow["address"]["city"] = "Shelbyville"
print(default_config["address"]["city"])
# Shelbyville <- the default was corrupted
# reset and use a deep copy so each order is independent
default_config["address"]["city"] = "Springfield"
order_config = copy.deepcopy(default_config)
order_config["address"]["city"] = "Shelbyville"
order_config["tags"].append("rush")
print(default_config["address"]["city"], default_config["tags"])
# Springfield ['standard'] <- default untouched
print(order_config["address"]["city"], order_config["tags"])
# Shelbyville ['standard', 'rush']

A shallow copy would let one order’s address change rewrite the customer’s default for every future order. The deep copy gives each order an independent address and tag list.

  • Copy from shared templates with deepcopy. When a cached default feeds many consumers that will mutate it, deep-copy on checkout so the template stays pristine.
  • Prefer construction over copying. Building a new object from fields is clearer than copying and mutating, and it avoids deep copy’s cost. Reach for deepcopy only when you genuinely need a duplicate.
  • Profile before deep-copying large structures. Deep copy walks every reachable object, which can be slow and memory-heavy on deep graphs. If you only need a shallow copy, do not pay for a deep one.
  • Handle cycles. deepcopy manages cycles through its memo automatically, so a self-referential structure copies without infinite recursion. A hand-rolled recursive copy does not.
  • Assuming a shallow copy is fully independent. A shallow copy of a nested structure shares the inner objects. Mutating an inner list or dict in the copy mutates the original.
  • Using list[:] and expecting a deep copy. Slicing a list makes a shallow copy. The inner elements are shared, so nested mutables are not duplicated.
  • Forgetting that the default argument is evaluated once. A mutable default like [] or {} is shared across calls. Use None and create a fresh object inside the function.
  • Deep-copying when a shallow copy or a new object would do. Deep copy is expensive. If the elements are immutable, a shallow copy is enough; if you are changing fields, construct a new object.
  • Customizing __copy__ without __deepcopy__ (or vice versa). Define both so callers get consistent behavior from copy.copy and copy.deepcopy. A partial definition surprises users of the other operation.
Need Use
New container, immutable or replace-only elements shallow copy (copy.copy, slicing, .copy())
Fully independent duplicate of a nested structure copy.deepcopy
Copy from a shared mutable template deepcopy at checkout
A new object with some changed fields construct a new object; avoid copying
Huge structure, top-level only changes shallow copy, not deep

copy.copy and copy.deepcopy are available in Python 3.9 and later, and have been standard for far longer. The __copy__ and __deepcopy__ protocols are part of the module. The examples here run on Python 3.9 and later with only the standard library.

1. What is the difference between a shallow copy and a deep copy? A shallow copy duplicates the container but reuses the elements, so nested mutable objects are shared. A deep copy recursively duplicates every reachable object, so the copy and original share nothing. The difference only matters when nested objects are mutable.

2. Why does dict.copy() not protect a nested dict? dict.copy() is a shallow copy: it makes a new outer dict whose values are the same references. A nested dict value is shared, so editing it through the copy edits it through the original. Use copy.deepcopy for a fully independent duplicate.

3. Explain the mutable default argument bug. Default argument values are evaluated once at function definition, so a default like def f(x=[]) uses the same list on every call that omits the argument. Appending to it leaks state across calls. The fix is a None sentinel and a fresh object created inside the function.

4. Senior scenario: copying a configuration tree with deepcopy is slow in production. What do you do? First measure where the cost is; deep copy walks every reachable object, so a wide or deep graph is expensive. Replace the blanket deepcopy with targeted copies: build new objects from the fields you actually change, use shallow copies where elements are immutable, or implement __deepcopy__ to copy only the mutable fields and share the rest. Profile to confirm the win, and avoid deep copy on structures that do not need full independence.

  • Shallow copy duplicates the container and shares the elements; deep copy duplicates everything.
  • copy.copy, slicing, and .copy() make shallow copies; copy.deepcopy makes deep ones.
  • The mutable default argument bug is shared-state in disguise; use a None sentinel.
  • Deep copy is correct but costly; prefer construction or shallow copy when they suffice.
  • Customize __copy__ and __deepcopy__ to give a class the right copy semantics.
  • dictionaries — the mutable mappings that shallow copy shares.
  • lists — slicing and .copy() for shallow list copies.
  • dataclasses — field(default_factory=...) is the type-safe fix for mutable defaults.
  • slots — memory layout that interacts with copying.