Mutability, references & copying
Explain why changing one list changed another and fix it with copies.
By Invicly Tech, , in Python Programming from Zero. About 12 minutes to read.
In short
Variables hold references to objects, not copies. If two names point to the same mutable list, changing it through one name changes what the other sees. Copies give you an independent object when you need one.
Think of it like this: Two names for one list are like two keys to the same house: rearrange the furniture and both see it.
Explained simply
Some objects can change after they are created, and some cannot. Lists, dicts and sets are mutable: you can add, remove and replace what is inside. Numbers, strings and tuples are immutable: every "change" really creates a new object.
A variable is a label stuck on an object, not a box holding its own copy. b = a sticks a second label on the same list. If you then change the list through b, you see the change through a as well, because there is only one list.
When you need an independent object, you must copy it on purpose. A shallow copy makes a new outer container but shares what is inside. A deep copy duplicates every level, so nothing at all is shared.
Many puzzling bugs come from this: a function that changes a list you passed in, a default argument that remembers old values, a grid where every row changes together. Once you picture names as labels pointing at objects, these bugs suddenly make sense and are easy to fix.
Press Play on a diagram to walk through it one step at a time.
- list, dict, set
- Can change in place
- Changes visible via every alias
- Not usable as dict keys
- int, float, str, tuple
- Operations create new objects
- Safe to share between names
- Hashable, usable as keys
- Same object, two names
- a is b is True
- Every change is shared
- New outer list
- Inner objects still shared
- Same as a[:] or list(a)
- Copies everything recursively
- Fully independent
- Slower for big data
- Mutable
- list
- dict
- set
- bytearray
- Immutable
- int, float, bool
- str
- tuple
- frozenset
- bytes, None
In depth
id, is and ==
Every object has an identity that never changes while it exists; id(obj) returns it as a number (in CPython, its memory address). a is b compares identities: are these two names pointing at the very same object? a == b compares values: do these objects hold equal contents? Two separate lists [1, 2] and [1, 2] are equal but not identical.
For immutable values the difference rarely matters, and CPython quietly reuses some objects to save memory: small integers from -5 to 256 and many short strings are shared. That is why 5 is 5 may print True while a large number computed two ways gives False. This caching is an implementation detail, so never use is to compare numbers or strings. Use == for values, and keep is for None and for checking aliasing.
- 1a = [1, 2]
a points at list L1
- 2b = a
b points at L1 too
- 3c = [1, 2]
A separate list L2 with equal values
- 4a == c is True
Same contents
- 5a is c is False
Different objects; a is b is True
Mutation vs rebinding
There are two very different ways to "change a variable". Mutation changes the object itself: a.append(3), a[0] = 9, d["k"] = 1. Every name pointing at that object sees the change. Rebinding points the name at a different object: a = a + [3] builds a new list and moves only a, so other names keep the old list.
The tricky one is +=. On a list, a += [3] mutates in place, exactly like extend(). On an int, string or tuple, which cannot change, += has to create a new object and rebind the name. Same symbol, different effect depending on mutability.
Function calls follow the same rules. Python passes a reference to the object (often called call by sharing). If the function mutates its parameter, the caller sees it. If the function assigns a new object to its parameter, only the local name moves, and the caller's variable is untouched.
- Changes the existing list
- a is b stays True
- b sees the new item
- Builds a new list
- Only a moves to it
- b keeps the old list
Shallow and deep copies in practice
There are several ways to make a shallow copy of a list: list(a), a[:], a.copy() and copy.copy(a). For a dict, dict(d) or d.copy(). They all create a new outer container whose slots point at the same inner objects. That is perfect for a flat list of numbers or strings, because immutable items never need copying.
Nested data is where shallow copies bite. Copy a list of lists, append to an inner list, and the original sees it, because the inner lists are shared. copy.deepcopy() walks the whole structure and copies every mutable level. It also handles objects that refer to each other. It is slower, and some objects, such as open files or network connections, cannot be deep-copied.
Often the clearest option is to build exactly the structure you need: [row[:] for row in grid] copies each row of a grid. The classic grid bug is [[0] * 3] * 3, which repeats one row object three times; [[0] * 3 for _ in range(3)] creates three separate rows.
Mutable default arguments
Default values are evaluated once, when the def statement runs, and then stored on the function object. With an immutable default like 0 or "" that is harmless. With def add(item, items=[]):, there is one list created at definition time, and every call that does not pass items appends to that same list. The first call returns [1], the second [1, 2], and so on.
The standard fix is a sentinel: write items=None and create a fresh list inside with if items is None: items = []. The same trap applies to dict and set defaults, and to values like the current time: def log(msg, when=datetime.now()) fixes the time at definition, not at each call.
Linters catch this. Ruff and flake8-bugbear report it as rule B006, which is one more good reason to run a linter from day one.
- Caller to add(): add(1)1add(1)
- add() to Default list: Use the one default list2Use the one default list
- add() to Caller: Returns [1]3Returns [1]
- Caller to add(): add(2)4add(2)
- add() to Default list: Same list again, append 25Same list again, append 2
- add() to Caller: Returns [1, 2]6Returns [1, 2]
Using immutability on purpose
Immutable objects are safe to share: no function can change a string or a tuple behind your back, which is why they can be dict keys and set items. Returning new objects instead of mutating inputs makes functions predictable and easy to test, as you saw with pure functions.
Mutation has its place too. Changing a large list in place avoids copying millions of items, and building a list with append in a loop is normal and efficient. The skill is to be deliberate: mutate objects your function created, and treat objects you received as read-only unless the function's name and docstring clearly say it changes them, like sort() or update().
Remember that immutability is shallow. A tuple holding a list cannot have its slots replaced, but the list inside can still change, and such a tuple is not hashable. For truly fixed records, use tuples of immutable values or frozen dataclasses.
Learn it in 4 short steps
About 30m each. Track them with a timer in your plan.
- 1Tell mutable from immutable types~30m
- 2See aliasing with two names, one list~30m
- 3Make shallow and deep copies~30m
- 4Avoid mutable default arguments~30m
Key points
- Assignment never copies; it just adds another name for the same object.
- == compares values; is checks whether two names point to the same object.
- A shallow copy duplicates only the outer container.
- Never use a mutable default like def f(items=[]); use None and create inside.
Key terms
Tap a card to flip it. 0/5 known
Examples
import copy
a = [[1, 2], [3]]
b = a # alias
c = copy.copy(a) # shallow
d = copy.deepcopy(a) # deep
a[0].append(99)
print(b[0], c[0], d[0]) # [1, 2, 99] [1, 2, 99] [1, 2]
def add_item(item, items=None):
if items is None:
items = [] # fresh list each call
items.append(item)
return itemsThe tic-tac-toe grid where every row changes
You build a 3 by 3 board and place an X in the top-left corner, but X appears in all three rows. Step 1: [[" "] * 3] * 3 creates one row list and repeats a reference to it three times. Step 2: grid[0] is grid[1] confirms all rows are the same object. Step 3: the comprehension runs [" "] * 3 three separate times, creating three independent rows. Step 4: now only one cell changes.
grid = [[" "] * 3] * 3
grid[0][0] = "X"
print(grid) # [['X', ' ', ' '], ['X', ' ', ' '], ['X', ' ', ' ']]
print(grid[0] is grid[1]) # True: one row, three references
grid = [[" "] * 3 for _ in range(3)]
grid[0][0] = "X"
print(grid) # [['X', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
print(grid[0] is grid[1]) # FalseA function that leaked changes through a shallow copy
promote_shallow() copies the user dict to be safe, yet the caller's tags still change. Step 1: u.copy() creates a new outer dict, but its "tags" value is the same list object. Step 2: appending to that list changes the caller's data. Step 3: copy.deepcopy() copies the inner list as well, so the new tag stays in the returned dict only. Step 4: the printout proves the original is safe this time.
import copy
def promote_shallow(u):
new = u.copy() # new outer dict, same inner list
new["tags"].append("vip")
return new
def promote(u):
new = copy.deepcopy(u) # inner list copied too
new["tags"].append("vip")
return new
user = {"name": "ana", "tags": ["new"]}
vip = promote(user)
print(user["tags"], vip["tags"]) # ['new'] ['new', 'vip']Quick reference
- a is b checks for the same object; a == b checks for equal values
- a.append(x) and a += [x] change the list in place; a = a + [x] makes a new list
- a[:], list(a) and a.copy() are shallow copies: nested lists stay shared
- copy.deepcopy(x) copies every level; slower, but fully independent
- Build grids with [[0] * cols for _ in range(rows)], never [[0] * cols] * rows
- Use def f(items=None): and create items = [] inside when it is None
- Never use is to compare numbers or strings; small-value caching makes it unreliable
- A tuple holding a list can still change inside, and it is not hashable
Common mistakes
- Mutable default arguments: the same list is reused across every call.
- Expecting list.copy() to copy nested lists too.
- Building a grid with [[0] * 3] * 3, which repeats one inner list three times.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Predict, then check: x = [1, 2, 3]; y = x; z = x[:]; x.append(4). Print y, z, y is x and z is x.
- Exercise 2medium
Fix def add_tag(tag, tags=[]): tags.append(tag); return tags so calls do not share data. Show that two calls without a tags argument each return a one-item list.
- Exercise 3hard
Write deep_clone(data) for nested lists and dicts without using the copy module. Prove that changing an inner list of the clone leaves the original alone.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does Python pass arguments by value or by reference?
- Neither exactly: it passes references to objects, often called call by sharing. A function can mutate a list you pass in, but assigning a new object to the parameter does not change the caller's variable.
- When should I use deepcopy?
- When you need a fully independent copy of nested mutable data, such as a config dict containing lists. For flat lists of numbers or strings, a shallow copy is enough and much faster.
- Why are strings immutable in Python?
- It makes them safe to share between names and usable as dict keys, and it lets Python reuse them. Methods like replace() simply return a new string.
- Why does my linter warn about a list as a default argument?
- The default list is created once and shared by every call, which Ruff and flake8-bugbear report as rule B006. Use None as the default and create the list inside the function.