MediumConcept

What is the difference between a shallow copy and a deep copy in Python?

Technology:
Python
Experience:
Junior,
Mid-level

Quick answer

A shallow copy creates a new container but reuses the same nested objects, while a deep copy recursively copies everything so the new object is fully independent.

Detailed explanation

With a shallow copy (copy.copy(), list.copy(), slicing items[:]), changing a nested list in the copy also changes it in the original, because both point to the same inner object. copy.deepcopy() duplicates the nested objects as well, handling circular references, but it is slower and uses more memory.

Plain assignment b = a does not copy at all: both names refer to the same object.

Example

python
import copy

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

original[0].append(99)
print(shallow[0])   # [1, 2, 99]  - shared inner list
print(deep[0])      # [1, 2]      - independent
  • PythonEasy

    What is the difference between a list and a tuple in Python?

    A list is mutable and can be changed after creation, while a tuple is immutable; tuples are slightly faster, use less memory and can be used as dictionary keys when their items are hashable.

    Intern 路 Junior 路 Data Structures
  • PythonMedium

    What are generators and the yield keyword in Python?

    A generator is a function that uses yield to produce values one at a time and remembers its state between calls, so it can process large or infinite sequences without holding everything in memory.

    Mid-level 路 Senior 路 Functions & Scope
  • PythonMedium

    How does Python manage memory and garbage collection?

    CPython frees objects mainly through reference counting, deleting an object as soon as nothing refers to it, and uses a cyclic garbage collector to clean up groups of objects that reference each other.

    Mid-level 路 Senior 路 Memory Management
  • PythonEasy

    What are *args and **kwargs in Python?

    *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary, which lets a function accept a variable number of arguments.

    Junior 路 Mid-level 路 Functions & Scope
  • PythonMedium

    Why should you not use a mutable default argument in Python?

    Default argument values are evaluated once when the function is defined, so a default list or dictionary is shared between every call that does not pass its own, causing data to leak between calls.

    Junior 路 Mid-level 路 Functions & Scope