Skip to content

Names, objects and the mutable default trap

BasicsConcept

You change b and a changes too, or a function quietly remembers what you passed it last time. Both come from one rule: assignment binds a name to an object, and never copies.

01 The surprise

Python
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4]

If you picture b = a as "put a copy of a in a box called b", this output makes no sense. You never touched a. The picture is wrong, not Python.

02 Names are labels on objects

In Python, every value is an object living on the heap. A name such as a is an entry in a table of names (a namespace) that refers to one object. Assignment name = expr works out the object for expr and makes the name refer to it. That is all it does.

Run the four lines below and watch the two tables separately: names on one side, objects on the other.

Python
a = [1, 2, 3]
b = a
b.append(4)
b = [9]
print(a, b)
Two names, then two objects
Step 1 of 6
names
Empty
objects
Empty
  • just made or bound
  • followed
  • changed in place
  • printed

The program has not run yet. No names, no objects.

03 Changing an object vs moving a name

Every line that seems to "change b" does one of two different things. It either mutates the object b refers to, which every other name for that object sees, or it rebinds b to another object, which nobody else sees.

Mutates
a = [1, 2]
b = a
b.append(3)
b[0] = 99
print(a) # [99, 2, 3]
Rebinds
a = [1, 2]
b = a
b = b + [3]
b = [99]
print(a) # [1, 2]

b + [3] builds a new list, so the name moves. Watch out for +=: on a list it calls extend and mutates in place, so b += [3] does change a. On a tuple, int or string, which cannot be changed, += builds a new object and rebinds.

Python
x = [1, 2]
y = x
y += [3]
print(x) # [1, 2, 3] (mutated)
t = (1, 2)
u = t
u += (3,)
print(t) # (1, 2) (rebound)

04 Same object or equal value

== asks whether two objects hold equal values. is asks whether two names refer to the same object. id(x) gives an object's identity, which in CPython is its memory address.

Python
a = [1, 2, 3]
b = a
c = list(a) # a new list with the same items
print(a is b) # True: one object, two names
print(a == c) # True: equal values
print(a is c) # False: two objects

Use is for None and other one-of-a-kind objects. Use == for values. x is 5 can look like it works, because CPython keeps one shared object for each small int from -5 to 256, but that is an implementation detail, and Python 3.8+ warns about it.

05 Calling a function binds a name too

Passing an argument is an assignment: the parameter name is bound to the caller's object. Mutating it inside the function changes the caller's object. Rebinding it only moves the local name.

Python
def add_item(items):
items.append("x") # mutates the caller's list
def reset(items):
items = [] # rebinds the local name only
cart = ["apple"]
add_item(cart)
reset(cart)
print(cart) # ['apple', 'x']

This is sometimes called call by sharing. It is neither "by value" (nothing is copied) nor "by reference" (the function cannot rebind the caller's name).

06 The mutable default trap

A def statement runs once. When it runs, Python evaluates each default value and stores the resulting object on the function. Every call that leaves the argument out gets that same object.

Python
def add(item, bucket=[]):
bucket.append(item)
return bucket
print(add(1)) # [1]
print(add(2)) # [1, 2]
print(add.__defaults__) # ([1, 2],)

There is one list, stored in add.__defaults__, and each call appends to it. Use None as the default and build a fresh object inside the body:

Shared list
def add(item, bucket=[]):
bucket.append(item)
return bucket
Fresh each call
def add(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket

The same applies to {}, set() and any object you build in a default. Linters flag it (Ruff and flake8-bugbear call it B006), so turn that rule on.

07 When you do want a copy

Copying is never automatic, so ask for it. Most copies are shallow: a new outer list whose slots point at the same inner objects.

Ways to get a "copy" of a = [[1], [2]]
CodeNew outer list?Inner lists
b = aNoShared: it is the same list
b = a.copy()YesShared
b = a[:]YesShared
b = list(a)YesShared
b = copy.deepcopy(a)YesCopied too, all the way down
for x in nums: x *= 2Changing the loop variablex is a name bound to each item in turn. x *= 2 on an int rebinds x; the list is untouched. Write nums = [x * 2 for x in nums].
rows = [[0] * 3] * 3Repeating a list* 3 repeats the reference, so all rows are one list. Use [[0] * 3 for _ in range(3)].
b = a.copy(); b[0].append(9)Trusting a shallow copyThe outer list is new, but b[0] and a[0] are the same inner list. Use copy.deepcopy when inner objects change.

08 Check yourself

Question

What does a = [1]; b = a; b = b + [2]; print(a) print?

Question

What does a = [1]; b = a; b += [2]; print(a) print?

Question

def f(x, seen=set()): seen.add(x); return len(seen). What do f(1), f(2), f(1) return?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?