On this page

Immutability in Python: A Functional Programming Deep Dive

Published on July 6, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Immutability is one of the two foundational pillars of functional programming — alongside expression‑oriented programming. An immutable object, once created, cannot be changed. This simple constraint eliminates entire categories of bugs: no accidental modifications, no hidden side effects, no “who changed this list?” mysteries that plague large‑scale systems. In Python, immutability is not the default — lists, dictionaries, and sets are mutable, while strings, tuples, and frozensets are immutable. This hybrid nature gives Python developers a choice: embrace mutability for convenience or adopt immutability for reliability. This lesson explains why immutability matters in functional programming, how to implement it effectively in Python, and how to balance the trade‑offs between performance, readability, and correctness.


What Is Immutability?​

An object is immutable if its state cannot be modified after creation. Once you create an immutable object, it remains unchanged for its entire lifetime. Any operation that would “modify” it actually creates a new object with the new value.

Consider a string in Python:


name = "Alice"

name = name.replace("A", "B")  # Creates a new string "Blice"

The original "Alice" string is not modified. The replace method returns a new string object, and the variable name is rebound to that new object. The old string remains unchanged (and will be garbage‑collected if no references point to it).

In contrast, a list is mutable:


items = [1, 2, 3]

items.append(4)  # Modifies the list in place

The list object itself is mutated. No new list is created. This difference — modifying in place versus creating a new object — is the core of immutability.


Why Immutability Matters in Functional Programming​

Functional programming is built on the idea that functions should be pure — deterministic, side‑effect‑free, and referentially transparent. Immutability is the mechanism that makes purity practical.

Eliminating Side Effects​

When data is immutable, a function cannot accidentally modify its inputs. This guarantees that functions behave predictably and do not have unintended consequences elsewhere in the program.


def add_item_immutable(items, new_item):

    return (*items, new_item)  # Creates a new tuple



def add_item_mutable(items, new_item):

    items.append(new_item)     # Modifies the original list

    return items

The immutable version is pure: it takes a tuple, creates a new tuple, and returns it. The original tuple is untouched. The mutable version modifies the list in place, which means any other part of the program that holds a reference to that list will see the change — often with surprising results.

Making Code Easier to Reason About​

When data cannot change, you never need to ask: “Has this value been modified by something else?” The answer is always no. This eliminates a class of bugs that are notoriously difficult to track down in large systems.

Enabling Safe Sharing​

Immutable data can be shared freely between functions, threads, and processes without the risk of data races or unexpected mutations. This is why immutable data structures are essential in concurrent and parallel programming.

Supporting Referential Transparency​

Referential transparency — the ability to replace an expression with its value without changing the program’s behaviour — depends on immutability. If a value can change, you cannot safely replace it with a fixed value.


Immutable Types in Python​

Python provides several built‑in immutable types:

Immutable TypeExampleNotesint``42All numbers are immutablefloat``3.14All numbers are immutablestr``"hello"Strings cannot be modified in placebool``TrueBooleans are immutabletuple``(1, 2, 3)Tuples are immutable sequencesfrozenset``frozenset([1, 2, 3])Immutable version of set``bytes``b"hello"Immutable byte sequencesNoneType``NoneThe None object is immutable

Every time you perform an operation that would “change” one of these values, Python creates a new object:


a = 10

b = a + 1  # b is a new int object, a is unchanged



s = "hello"

t = s.upper()  # t is a new string object, s is unchanged



lst = [1, 2, 3]

tpl = tuple(lst)  # tpl is a new tuple

Why Are Some Types Mutable?​

Python provides mutable alternatives for cases where performance or convenience is more important than safety. Lists are mutable because they are often used in situations where in‑place modification is more efficient than creating new objects. Dictionaries are mutable because they are designed for dynamic key‑value storage.

The existence of mutable types does not mean you must use them. Functional programming in Python is about choosing immutability whenever it makes sense, not about eliminating mutability entirely.


Achieving Immutability in Python​

Beyond using built‑in immutable types, there are several techniques for enforcing immutability in your own code.

Using Tuples Instead of Lists​

Tuples are the simplest immutable sequence. Anywhere you would use a list that should not change, use a tuple instead:


# Mutable

coordinates = [10, 20]

coordinates[0] = 30  # Allowed



# Immutable

coordinates = (10, 20)

# coordinates[0] = 30  # TypeError: 'tuple' object does not support item assignment

Tuple unpacking and concatenation work naturally, and tuples can be used as dictionary keys (lists cannot).

Using Frozensets Instead of Sets​

A frozenset is the immutable equivalent of a set. It supports all the same set operations but cannot be modified after creation:


unique_items = frozenset([1, 2, 3, 3, 4])  # frozenset({1, 2, 3, 4})

# unique_items.add(5)  # AttributeError: 'frozenset' object has no attribute 'add'

Frozensets are hashable, so they can be used as keys in dictionaries or elements in other sets.

Using Namedtuples for Lightweight Immutable Objects​

The namedtuple factory function creates tuple subclasses with named fields:


from collections import namedtuple



Point = namedtuple("Point", ["x", "y"])

p = Point(10, 20)

# p.x = 30  # AttributeError: can't set attribute

Namedtuples are immutable, memory‑efficient, and provide a clean interface for small data objects.

Using Frozen Dataclasses​

Python 3.7 introduced dataclasses, and you can make them immutable by setting frozen=True:


from dataclasses import dataclass



@dataclass(frozen=True)

class Person:

    name: str

    age: int



p = Person("Alice", 30)

# p.age = 31  # FrozenInstanceError: cannot assign to field 'age'

This is the most convenient way to create custom immutable classes in modern Python.

Using @property for Read‑Only Attributes​

If you need a class with computed or read‑only attributes, you can use @property to expose values without allowing assignment:


class Circle:

    def __init__(self, radius):

        self._radius = radius



    @property

    def radius(self):

        return self._radius



    @property

    def area(self):

        return 3.14159 * self._radius ** 2

However, this does not prevent mutation of the underlying _radius attribute. For true immutability, use frozen=True dataclasses or namedtuple.

Creating New Objects Instead of Mutating​

The functional approach to “changing” data is to create a new object with the desired changes:


# Mutable approach

def add_user(users, new_user):

    users.append(new_user)  # Mutates the list



# Immutable approach

def add_user(users, new_user):

    return users + [new_user]  # Creates a new list

This pattern extends to dictionaries and custom objects:


# Mutable

config["debug"] = True



# Immutable

new_config = {**config, "debug": True}

The {**config, "debug": True} syntax creates a new dictionary that contains all the keys from config plus the new key‑value pair.


Persistent Data Structures​

Creating new copies of large data structures can be expensive. This is where persistent data structures come in. A persistent data structure preserves the previous version of itself when modified, sharing as much structure as possible with the new version to minimise memory and time overhead.

The Pyrsistent Library​

The pyrsistent library provides persistent (immutable) versions of Python’s built‑in data structures:


from pyrsistent import pvector, pmap, pset



# Persistent vector (like a tuple but with more operations)

v = pvector([1, 2, 3])

v2 = v.append(4)  # v is unchanged, v2 is a new vector

v3 = v2.set(0, 10)  # v2 is unchanged, v3 has first element set to 10



# Persistent map (like a dict)

m = pmap({"a": 1, "b": 2})

m2 = m.set("c", 3)  # m is unchanged, m2 has new key

m3 = m2.remove("a")  # m2 is unchanged, m3 has key "a" removed

Pyrsistent uses structural sharing internally, so these operations are efficient even on large collections.

Built‑In Alternatives​

For many use cases, Python’s built‑in immutable types are sufficient. Tuples and frozensets are persistent by nature — they cannot be modified, so any “modification” creates a new object. The copy module provides copy.deepcopy for creating independent copies of mutable objects, though this does not provide structural sharing.


Performance Considerations​

Immutability has a performance cost: creating new objects requires allocating memory and copying data. However, in many cases, the cost is negligible compared to the benefits of correctness and maintainability.

When Immutability Is Faster​

Immutable objects are often faster in certain contexts:

When Mutability Is Faster​

Mutability is faster when you need to perform many incremental updates on large data structures. In these cases, persistent data structures like those in pyrsistent can help by providing efficient structural sharing.

The Trade‑Off​

The choice between mutability and immutability is a trade‑off between performance and correctness. In performance‑critical code, mutability may be justified. In most code, immutability’s benefits — fewer bugs, easier reasoning, safer concurrency — outweigh the performance costs.


Practical Patterns for Immutability​

1. Use tuple for Fixed‑Length Sequences​

If you know the length of a sequence ahead of time, use a tuple:


# Good

colors = ("red", "green", "blue")



# Avoid if the sequence should not change

colors = ["red", "green", "blue"]

2. Use frozenset for Unchanging Sets​

If a set of values is fixed, use a frozenset:


valid_statuses = frozenset(["active", "pending", "completed"])

3. Use namedtuple or Frozen Dataclasses for Data Objects​

For data containers, prefer immutable classes:


@dataclass(frozen=True)

class Config:

    host: str

    port: int

    debug: bool = False

4. Return New Objects from Functions​

When a function needs to update data, return a new object rather than mutating the input:


def update_config(config, **kwargs):

    return Config(**{**config.__dict__, **kwargs})

5. Avoid Global Mutable State​

Global variables that are mutable are a common source of bugs. Use immutable constants where possible, and avoid global state in functional code.


Immutability and Python’s Reference Model​

Python uses a reference model: variables are labels that point to objects in memory. This means that when you pass an object to a function, you are passing a reference to the same object, not a copy.

With mutable objects, this can lead to unexpected behaviour:


def append_to_list(lst):

    lst.append(4)



items = [1, 2, 3]

append_to_list(items)

print(items)  # [1, 2, 3, 4] — the list was modified!

With immutable objects, this problem disappears:


def add_to_tuple(tpl, value):

    return tpl + (value,)



items = (1, 2, 3)

new_items = add_to_tuple(items, 4)

print(items)      # (1, 2, 3) — unchanged

print(new_items)  # (1, 2, 3, 4)

Immutable objects cannot be modified through references, so you never have to worry about accidental mutations.


Common Mistakes and How to Avoid Them​

1. Assuming a Variable Is Immutable Because It Is a Tuple​

A tuple is immutable, but if it contains a mutable element, that element can still be changed:


tpl = ([1, 2], 3)

tpl[0].append(4)  # This works! The list inside the tuple is mutable

print(tpl)  # ([1, 2, 4], 3)

To create a truly immutable nested structure, use immutable containers throughout: tuple of tuple, frozenset, and frozen dataclasses.

2. Using Mutable Default Arguments​

Default arguments are evaluated once at function definition time. If you use a mutable default, it is shared across all calls:


def add_item(item, items=[]):  # Bad!

    items.append(item)

    return items

Use None as the default and create a new object inside the function:


def add_item(item, items=None):

    if items is None:

        items = ()

    return items + (item,)

3. Confusing Reassignment with Mutation​

Reassigning a variable does not mutate the object; it just changes what the variable points to:


x = [1, 2, 3]

x = x + [4]  # x now points to a new list, the old list is unchanged

This is safe. The problem is mutation: x.append(4) modifies the list in place.


Summary​

Immutability is a cornerstone of functional programming in Python. By using immutable data structures and writing functions that do not modify their inputs, you eliminate entire categories of bugs, make your code easier to reason about, and enable safe sharing in concurrent systems. Python provides a rich set of built‑in immutable types — tuple, frozenset, str, int — and tools like namedtuple and frozen dataclasses for custom immutable objects. For performance‑critical applications, persistent data structures like those in pyrsistent offer efficient structural sharing. While immutability comes with some performance costs, the benefits in correctness, maintainability, and developer confidence far outweigh the trade‑offs in most applications.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Structural Pattern Matching

Next

Pure Functions