Mutability and Aliasing

Two names pointing at one list, why changing one changes both, and the difference between rebinding a name and mutating an object.

Overview

Two names pointing at one list, why changing one changes both, and the difference between rebinding a name and mutating an object.

In this guide
  1. Assignment does not copy
  2. Rebinding versus mutating
  3. Inside functions
  4. Immutable types dodge the question
  5. The multiplication trap
  6. Which types are which
  7. Equality and identity
  8. Passing to functions, stated precisely
  9. Defensive copies
  10. Watching it happen with id()
  11. The augmented assignment asymmetry
  12. A tuple is immutable, its contents are not
  13. Where this actually bites
  14. A model that fits in your head
  15. Choosing immutability in your own code
  16. Questions people ask about Mutability and Aliasing
  17. Mutability and Aliasing: recap in one screen
  18. Aliasing across threads is this bug with the timing removed

aliasing.py

aliasing.py Python 3
Output

                    

mutable_arguments.py

mutable_arguments.py Python 3
Output

                    

Worth knowing

b = a gives the object a second name. It does not copy anything.
is asks "the same object?"; == asks "the same contents?".
Rebinding a name inside a function is local. Mutating the object is visible to the caller.
[[0]*3]*3 repeats one inner list three times. Use a comprehension.

Mutability and Aliasing: A Practical Guide

A name in Python is a label attached to an object, not a box holding a value. Once that clicks, a whole family of confusing action turns obvious.

Assignment does not copy

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

b = a attaches a second label to the same list. There is one list and two names for it. A change through either name is visible through both. a is b is True. That is the test for "same object," not ==, which checks contents.

To get a separate list, ask for one: a[:], list(a), or a.copy().

This behavior is called aliasing, and it is the source of some of the most confusing bugs beginners encounter. You think you have two independent lists, but you have one list with two names. Append to one and both grow. Sort one and both rearrange. Clear one and both become empty.

The reason Python works this way is performance. Lists can be large. If every assignment made a full copy, a simple function call would duplicate the entire list. Instead, assignment just creates a new reference to the same object. Copying happens only when you ask for it explicitly.

Mutability means an object can be changed after it is created. Lists, dictionaries, and sets are mutable. Strings, integers, floats, and tuples are immutable. You cannot change a character in a string or an element in a tuple. Any operation that appears to modify an immutable object actually creates a new one.

The distinction matters most with function arguments. When you pass a list to a function, the function receives a reference to your list, not a copy. If the function modifies the list, your original changes too. That is sometimes intentional and sometimes a bug. If the function is not supposed to modify the list, pass a copy: f(my_list[:]) or f(my_list.copy()).

Rebinding and mutating are different operations, and confusing them is a common source of errors. x = [1, 2, 3] followed by x = [4, 5, 6] rebinds x to a new list. The old list still exists if another variable points to it. x.append(4) mutates the existing list. The question is: does this line change what x points to, or does it change the object x already points to?

Default arguments make this worse. def f(items=[]): creates one list object at function definition time. Every call that uses the default shares that same list. If the function appends to it, the next call sees the leftover items. The fix is def f(items=None): followed by if items is None: items = [].

This page covers aliasing, mutability versus immutability, how function arguments share references, rebinding versus mutating, and the mutable default argument trap.

Rebinding versus mutating

This is the gap that shows the rest:

y = [9, 9]    # rebinding: point y at a different object
y.append(3)  # mutating: change the object y points at

Rebinding affects only that name. Mutating affects each name pointing at that object. Both use y. This Is why they look similar and behave nothing alike.

Inside functions

def add_zero(items):
    items.append(0)  # caller sees this
def replace(items):
    items = [9, 9]    # caller sees nothing

The param is another name for the caller's object. Mutate it and the caller's list changes. Rebind it and you've only pointed the local name elsewhere.

This isn't "pass by ref" or "pass by value". It's simply the same naming rule as all over else in the language.

Immutable types dodge the question

Numbers, strings and tuples can't be mutated. There's no way for one name to change what another sees. n += 1 inside a function must rebind. There's no other option. That is why the whole issue only ever comes up with lists, dicts and sets.

The multiplication trap

grid = [[0] * 3] * 3
grid[0][0] = 1  # every row changes

[0] * 3 builds one row. Timesing the outer list by 3 doesn't build three rows. It stores three refs to the same row. Setting one cell appears to set three.

grid = [[0] * 3 for _ in range(3)]

The comprehension tests [0] * 3 afresh each pass. There really are three lists. This is the same rule as the mutable default arg: one object created once, shared all over.

Which types are which

The gap is worth storing as a list, because it shows action across the whole language.

Immutable: int, float, bool, str, bytes, tuple, frozenset, None. Mutable: list, dict, set, bytearray, and nearly each class you write yourself.

each rule about aliasing, dict keys, default args and copying falls out of that split. Immutable objects can be shared without risk, which is why they can be dict keys and set members and safe defaults. Mutable objects can't.

Equality and identity

Two separate questions, and Python has an operator for each:

a == b      # do they hold the same value?
a is b      # are they the same object?

Two lists with the same contents are equal and aren't the same. Confusing the two makes code that works by accident, above all with small ints and short strings, which Python caches: x = 256. Y = 256. X is y is often True, and the same test with 257 is often False. That is an setup detail and just why is should be reserved for None and for genuine identity questions.

Passing to functions, stated precisely

Python is neither pass-by-value nor pass-by-ref in the C sense. What is passed is a ref to the object, by value - the function gets its own name pointing at the caller's object.

So the function can mutate the object and the caller sees it, and the function can rebind its own name and the caller doesn't. Both facts come from the same mechanism, and once you hold "names point at objects" in your head, no further rule is needed.

Defensive copies

When a function stores a thing it was given, it's worth thinking about who else holds it:

class Basket:
    def __init__(self, items):
        self.items = list(items)     # our own copy

Without the copy, the caller's list and the object's list are the same list, and a later change on either side surprises the other. Copying at the boundary costs one call and drops an entire category of bug where two parts of a program share state neither of them knows about.

The same thinking applies on the way out: returning self.items right hands callers a handle on your internals. Returning list(self.items) or a tuple keeps the boundary intact.

Watching it happen with id()

id() returns a number spotting an object for if it exists, which turns the whole topic from an assertion into a thing you can check:

a = [1, 2]
b = a
before = id(a)

a.append(3)
print("after append :", id(a) == before, b)

a = a + [4]
print("after rebind :", id(a) == before, b)
after append : True [1, 2, 3]
after rebind : False [1, 2, 3]

The first line mutated the object. So The id is unchanged and b — the other name for that same object. Sees the new item. The second line built a different list and pointed a at it. The id changed and b still refers to the first. This Now has three items rather than four.

each confusing aliasing bug is one of those two lines in disguise.

The augmented assignment asymmetry

a += [3] and a = a + [3] look like the same statement written two ways. For lists they aren't:

a = [1, 2]
b = a
a += [3]
print(a, b)

a = [1, 2]
b = a
a = a + [3]
print(a, b)
[1, 2, 3] [1, 2, 3]
[1, 2, 3] [1, 2]

+= on a list calls __iadd__. This Extends the existing list in place and then rebinds the name to that same object. So every other name sees the change. a + [3] builds a new list and only then rebinds, leaving b alone.

For numbers, strings and tuples there's no in-place option, so += always behaves like the second form. This is why += feels steady right up until the first time it's used on a list that someone else is also holding.

A tuple is immutable, its contents are not

t = ([1, 2], "fixed")

t[0].append(3)
print(t)

try:
    t[1] = "changed"
except TypeError as e:
    print("TypeError:", e)
([1, 2, 3], 'fixed')
TypeError: 'tuple' object does not support item assignment

The tuple ensures that its slots keep pointing at the same objects. It promises nothing about those objects. A tuple of lists is so not a frozen structure, and — the hands-on consequence — it can't be used as a dict key. Hashing it has to hash its contents and lists are unhashable.

The sharpest corner in the language sits here:

t = ([1],)
try:
    t[0] += [2]
except TypeError as e:
    print("TypeError:", e)
print(t)
TypeError: 'tuple' object does not support item assignment
([1, 2],)

It raised and it worked. t[0] += [2] extends the list in place, and then tries to assign the result back into the tuple slot. This Fails. The mutation has already happened by then. Nothing about this is worth leaning on. It's worth recognising, because the error message points at the tuple while the damage is in the list.

Where this actually bites

The rule is simple and the bugs aren't. In real code the two names for one object are often far apart. Four shapes account for most of them.

A shared default. A function with def add(item, target=[]) creates that list once, when the function is defined, and each call that doesn't pass one uses the same list. Items build up across calls that look free. The fix is target=None and if target is None: target = [] in the body.

A configuration dict passed around. One module reads a settings dict, tweaks a value "just for its own use", and every other module sees the change. This is the hardest version to find. The code that made the change and the code that misbehaves may be in different files with nothing linking them.

A cached object handed to callers. A function that builds a list once and returns the same list each time is fast and dangerous: the first caller to mutate the result has changed what each later caller receives. Returning a copy, or a tuple, closes it.

A class field holding a list. Written on the class rather than in __init__, it belongs to the class. So Each instance appends to the same one. Instances that were meant to be free quietly share state.

What the four have in common is that no one wrote b = a. The second name arrived through an arg, a return value, a default or a class body. That is why "set doesn't copy" is worth internalising rather than storing: the aliasing is rarely visible on the line where the bug appears.

A model that fits in your head

Two sentences cover all on this page.

Names point at objects. A name isn't storage. It's a label. set moves a label. a few labels can point at one object, and the object has no idea how many.

Some objects can change, and some can't. If an object can change, then each label pointing at it sees the change, because there's only one object. If it can't, the question never arises.

All else follows. Why does mutating a list arg affect the caller? The param is another label on the same object. Why does n += 1 inside a function not affect the caller? ints can't change. So += must build a new one and move the local label to it. Why is a tuple of lists not frozen? The tuple's labels can't be moved. The objects they point at can still change.

When a thing surprising happens, the productive question isn't "was this passed by value or by ref" but "how many names point at this object, and did that line move a label or change an object". id() answers the first half and the code in front of you answers the second.

Choosing immutability in your own code

Once the gap is clear, it turns a design choice rather than a fact about builtins. Making your own objects immutable drops the entire class of bugs above, and Python gives you a few ways to do it.

A NamedTuple or a dataclass declared with @dataclass(frozen=True) makes a class whose fields can't be reassigned after build. Attempting it raises rather than silently succeeding. This Turns a subtle shared-state bug into an immediate error at the line that caused it. Both are hashable, so they can be dict keys and set members, and both give you a readable repr for free.

The pattern that follows is to build a new object rather than edit an existing one. A method that would have changed self.total instead returns a new instance with the new total, and callers rebind. This costs an allocation and buys the ensure that nothing you handed to another part of the program can change underneath it.

It isn't the right default for all. A large object that changes often — a buffer being filled, a cache, any of it speed-sensitive — is better mutable, and Python's builtins reflect that. The handy habit is to reach for immutability for the things that travel: configuration, coords, records read from a file, any of it passed between modules or stored in a dict. Keep mutability local. Here You can see each name that points at the object.

Questions people ask about Mutability and Aliasing

How do I copy a list properly? list(a), a[:] or a.copy() for one level. copy.deepcopy(a) when the items are themselves mutable and need copying too.

Is is ever right for checking values? Only for None, True and False. All else should use ==.

Why did my dict change when I only edited a copy? Because the copy was shallow and the value you edited is shared between both dicts.

Are function args copied? No. The function gets another name for the same object. This Is why mutating a list arg is visible to the caller.

Why can a tuple be a dict key but not a list? Keys must hash to a stable value, and a list's contents can change. This Would leave it filed in the wrong place.

Does sorted(x) change x? No, it returns a new list. x.sort() is the in-place one, and it returns None — assigning its result is a common way to lose a list.

What about strings, do I need to copy them? Never. They can't be changed, so sharing one is always safe.

Mutability and Aliasing: recap in one screen

  • A name is a label on an object. Set moves the label and never copies.
  • Mutating changes the object each name can see. Rebinding changes one name.
  • += mutates in place for lists and rebinds for immutables — the same syntax, two actions.
  • Immutable contents can hold mutable objects. So A tuple is only as frozen as what is in it.
  • Copy at the boundary when you store or return a caller's container.

Aliasing across threads is this bug with the timing removed

Two names for one list is a small surprise while you read a function top to bottom. Two *threads* holding the same alias is the same fact minus the ability to find it: you can no longer point at the line where the object changed, because it changed between two of your own lines.

Nothing about mutability is different there. What is different is that "who else holds a ref to this?" stops being answerable by reading the enclosing function.

The defensive move is the one this page already argues for: copy at the boundary, or hand over a thing immutable. It's cheaper than a lock, and unlike a lock it can't be forgotten at one call site.

Check yourself

0 of 3

Answer without scrolling back up.

  1. After `a = [1]; b = a; b.append(2)`, what is `a`?

  2. A function does `items = [9]`. What does the caller see?

  3. Why does `[[0]*3]*3` misbehave?

Cheat sheet

Mutability and Aliasing

See why assigning a list to a second name does not copy it, and how mutability makes two variables change the same object at once.

PYTHON · vizlearn.in/python/mutability_and_aliasing.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.

Teaching a course with this? Individual teachers can use it freely; for a whole department or programme, see institutional licences.