Python 101 · Shallow and Deep Copy

Jan 9, 2016 | Tech Software

Index
Index

Mutable and Immutable Types

Data Copy Behavior
Immutable
  • Data cannot be modified after creation, modifications create new objects
  • Shallow and deep copy all refer to the original object; no copy needed, modifications won't affect original data
Mutable
  • Data can be modified directly after creation; modifications do not create new objects
  • The difference between shallow and deep copy becomes apparent with nested structures of mutable types; not much with single-layer mutable types

Nested Mutable Data

Feature Shallow Copy Deep Copy
Scope Only copies the outer container, does not copy nested elements. Recursively copies the outer container and all nested elements, including multi-level nested mutable types.
Memory Nested mutable elements share the same memory address. No memory sharing at all, the new object is completely independent from the original.
Impact Modifying nested mutable elements will affect the original object. Modifying either the new or the original object will not affect the other.
Implementation copy.copy(), [:], or foo.copy() if supported copy.deepcopy(), the only built-in valid method.
Performance Lower overhead. Higher overhead due to recursive copying.

Custom Classes

  • in general, use copy.copy() and copy.deepcopy() directly
  • the difference only becomes apparent when dealing with nested mutable structures in custom classes, similar to built-in types
  • if necessary, use __copy__(self) and __deepcopy__(self, memo) for customized behavior

Examples

  • Immutable Types

  • Mutable Types

  • Nested Shallow Copy

  • Nested Deep Copy

  • Class by Module

  • Class by Dunders