Stop 05 · Built-in Data StructuresTopics · 6/9

Mutable vs Immutable & Copying

Part of the Python Roadmap

In short

One of the most confusing bugs for new Python programmers: you change one list and another 'separate' list changes too. Understanding mutability and copying makes that bug disappear forever.

Lists, dicts and sets are mutable and can change in place, while ints, strings and tuples are immutable. Assigning a list to a new name doesn't copy it, so use .copy() for a shallow copy or copy.deepcopy() for nested data.

The jaadu feeds a page into a photocopier and compares the warm fresh copy with the original held up in the other hand.

Think of it like this

A shared Google Doc vs a photocopy

If your friend gives you the link to their Google Doc, you're both editing the same document. If they hand you a photocopy, your scribbles don't touch the original. In Python, b = a shares the link. a.copy() makes a photocopy. And a deep copy photocopies every page stapled inside it too.

Watch it happen

Shallow copy or deep copy?

Shallow: a.copy()

  • New outer list
  • Inner lists still shared
  • Fast and fine for flat data
  • Also list(a), a[:], dict(d)

Deep: copy.deepcopy(a)

  • New outer list
  • New copies of everything inside
  • Slower but fully independent
  • Use for nested lists or dicts

Flat list of numbers or strings? A shallow copy is enough. Lists inside lists or dicts inside dicts? Use deepcopy so edits never leak back.

The big ideas

What you need to know

Mutable types

list, dict and set can change in place. Methods like append or update modify the same object.

Immutable types

int, float, str, tuple and bool never change. 'x' + 'y' or n + 1 creates a brand new object.

Assignment is a label

b = a doesn't copy anything. Both names point to one object. Check with a is b.

Copy on purpose

Use .copy() or slicing for a shallow copy, and copy.deepcopy() when the data is nested.

See it in code

Walk through the code

python
1import copy2 3a = [1, 2, 3]4b = a                 # same list, two names5b.append(4)6print(a)              # [1, 2, 3, 4]7print(a is b)         # True8 9c = a.copy()          # shallow copy10c.append(5)11print(a)              # [1, 2, 3, 4], unchanged12 13grid = [[0, 0], [0, 0]]14shallow = grid.copy()15deep = copy.deepcopy(grid)16shallow[0][0] = 917print(grid)           # [[9, 0], [0, 0]], inner list was shared18deep[1][1] = 719print(grid)           # still [[9, 0], [0, 0]]20 21name = "ravi"22name.upper()          # returns a new string23print(name)           # ravi, strings never change in place

1/5b = a only adds a second label. Appending through b changes what a sees, and a is b is True.

Two names for one list, a shallow copy, the nested-list trap and immutable strings.

Save yourself the pain

Common mistakes

Oops

Creating a grid with [[0] * 3] * 3 and seeing every row change together.

Do this instead

That repeats the same inner list three times. Use [[0] * 3 for _ in range(3)] to get separate rows.

Oops

Using a mutable default like def add(item, bag=[]):

Do this instead

The default list is shared across calls. Use bag=None and create a new list inside the function.

Oops

Calling text.replace('a', 'b') and expecting text to change.

Do this instead

Strings are immutable. Assign the result: text = text.replace('a', 'b').

Your mission

Spot the shared list

~20 min

Quick check

a = [[1], [2]]; b = a.copy(); b[0].append(9). What is a now?

Go deeper

  1. 1Assign b = a for a list, change b, and see that a changes too.
  2. 2Compare a shallow copy and a deep copy on a list of lists.
  3. 3Use id() to check whether two names point to the same object.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge