Names, objects and the mutable default trap
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
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.
- 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.
a = [1, 2]b = ab.append(3)b[0] = 99print(a) # [99, 2, 3]
a = [1, 2]b = ab = 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.
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.
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.
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.
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:
def add(item, bucket=[]):bucket.append(item)return bucket
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.
| Code | New outer list? | Inner lists |
|---|---|---|
| b = a | No | Shared: it is the same list |
| b = a.copy() | Yes | Shared |
| b = a[:] | Yes | Shared |
| b = list(a) | Yes | Shared |
| b = copy.deepcopy(a) | Yes | Copied 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.