Mutation

Table of Contents

1. Mutation

Mutation is the ability of certain data types, like lists, to be changed or modified after they are created. This means that their contents can be altered without creating a new object.

In Python, everything is an object and variables are pointers to those objects. A data type that is mutable changes the object itself without the need to create a new object (and thereby modifying the pointer). These pointers are known as the identity of the variable. When two variables point to the same object, we say those variables have the same identity.

In this way, if we have two variables pointing to the same mutable data type, like a list, changing one of the variables will change the other. However, the reason why if we do a = 3, b = a, but then b = 5 doesn't change a to be 5 is because integers are immutable, which means the assignment b = 5 created a new object independent of the original a object.

1.1. Identity Operators

We can use the is operator to check if two variables have the same identity, i.e. they evaluate to the same object: <exp0> is <exp1>.

We can use the == operator to check if two variables evaluate to the same value.

1.2. Mutable Default Arguments

A mutable default argument is dangerous because it stays as part of the function value. In other words, the following function's default argument mutates every time you call it:

def f(s=[]):
    s.append(5)
    return len(S)

one = f()     # 1
two = f()     # 2
three = f()   # 3

1.3. Persistent Local State

We can use mutable values to keep track of a persistent local state. To do so, we can define a mutable sequence in the parent frame of a function, which can change over time as the function mutates it:

def make_withdraw_list(balance):
    b = [balance]
    def withdraw(amount):
        if amount > b[0]:
            return 'Insufficient funds'
        b[0] = b[0] - amount
        return b[0]
    return withdraw
Last modified: 2025-10-07 15:52