Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 149 ยท Data Types

Shallow and Deep Copies

Understand aliasing in Python. Learn why assignment does not copy, how shallow copies share nested data, and when to use copy.deepcopy.

One of the most surprising moments for new Python programmers is changing one list and watching a different variable change too. The cause is that assignment in Python never copies data. It only attaches another name to the same object. Once you understand that, copying becomes a choice with three levels: no copy (an alias), a shallow copy and a deep copy.

In this lesson you'll see each level in action, learn which ways of copying are shallow, meet the copy module and copy.deepcopy(), and learn how to customize copying for your own classes. If names pointing at objects still feels fuzzy, a quick look at Variables and Memory Management helps.

Assignment makes an alias

When you write b = a, both names refer to one object. Mutating it through either name is visible through both:

Python Aliasing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Immutable objects such as numbers, strings and tuples can't be changed, so aliases to them are harmless. The trouble is limited to mutable objects: lists, dictionaries, sets and most instances of your own classes.

flowchart LR
    a(["a"]) --> L["list [1, 2, 3, 4]"]
    b(["b"]) --> L

After b = a there is only one list. Both names lead to it.

Shallow copies

To get an independent top-level container, make a shallow copy. Several spellings do the same job:

Python Ways to make a shallow copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Lists, dictionaries and sets all have a .copy() method. copy.copy() works on almost anything. The new container is separate, so adding or removing items in one leaves the other alone.

The catch: nested objects are shared

A shallow copy creates a new outer container but fills it with references to the same inner objects. For a list of numbers that doesn't matter. For a list of lists, it does:

Python Shallow copies share inner objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

flowchart TB
    G["grid"] --> R1["inner list A"]
    G --> R2["inner list B"]
    S["shallow copy"] --> R1
    S --> R2

Two outer lists, but both point at the same two inner lists.

This is also the reason that [[0] * 3] * 3 is a classic bug: it repeats the same inner list three times. Build grids with a comprehension, such as [[0] * 3 for _ in range(3)], which makes a fresh inner list for each row.

Deep copies

copy.deepcopy() copies the container, then copies everything inside it, recursively. The result shares nothing mutable with the original:

Python deepcopy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The deep copy kept qty at 2 because it owns its own nested dictionaries. Use it when you need a truly independent snapshot, for example before running an experiment on a configuration or when saving "undo" states.

Deep copies cost time and memory proportional to the size of the data, so don't use them reflexively. If you only change the outer layer, a shallow copy is enough. If your data is plain JSON-like values, rebuilding with a comprehension can be clearer.

Cycles and shared references

deepcopy() keeps a memo of objects it has already copied, so it handles cycles and preserves sharing inside the copy:

Python deepcopy with cycles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Copying your own objects

copy.copy() and copy.deepcopy() work on instances of your classes too, copying their attributes. You can take control by defining __copy__ and __deepcopy__:

Python Custom copy behavior

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The memo dictionary is passed through to nested calls so cycles keep working. Dataclasses (Data Classes) have dataclasses.replace() for making a modified copy of an immutable-style record, which is often neater than a deep copy.

Note: Some objects cannot be copied, such as open files, sockets and locks. deepcopy raises TypeError for them. Copy the plain data and recreate the resource instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. After b = a where a is a list, what is true?

    Assignment never copies. It binds a second name to the same object, so a is b is True.
  2. 2. rows = [[1], [2]] and copy = rows.copy(). What does copy[0].append(9) do to rows?

    list.copy() is shallow, so both lists contain the same inner list objects. Mutating an inner list shows up in both.
  3. 3. Which function copies a nested structure completely?

    deepcopy() copies nested objects recursively. The others make shallow copies.
  4. 4. Why is [[0] * 3] * 3 a bad way to make a 3x3 grid?

    Multiplying a list repeats references to the same inner list. Use a comprehension to create separate rows.

Summary

  • Assignment creates an alias, not a copy. Aliases matter only for mutable objects.
  • A shallow copy (.copy(), list(x), x[:], copy.copy()) duplicates the outer container and shares the inner objects.
  • copy.deepcopy() duplicates everything recursively and handles cycles through a memo.
  • Define __copy__ and __deepcopy__ to customize copying of your own classes.
  • Deep copies are slower, so use them only when nested data must be independent.

Next: Arithmetic Operators, where you'll start calculating with Python.