Immutable vs Mutable Objects in Python 2026

Writing Functions Mar 16, 2026

Immutable vs Mutable Objects in Python 2026

Understanding the difference between immutable and mutable objects is fundamental to writing correct, predictable, and efficient Python functions. In 2026, this knowledge directly impacts code safety, performance, and debugging experience.

TL;DR — Key Takeaways 2026

  • Immutable: int, float, str, tuple, frozenset, bytes — cannot be changed after creation
  • Mutable: list, dict, set, custom classes — can be modified in place
  • Immutable objects are safe to pass to functions
  • Mutable objects can cause unexpected side effects if modified inside functions
  • Prefer immutable data structures when possible for safer code

1. Immutable vs Mutable Behavior


# Immutable - behaves like "pass by value"
def increment(n: int) -> int:
    n += 1          # Creates a new integer object
    return n

x = 10
increment(x)
print(x)            # Still 10

# Mutable - can be modified in place
def add_item(items: list) -> None:
    items.append("new")   # Modifies the original list!

my_list = ["a", "b"]
add_item(my_list)
print(my_list)      # ['a', 'b', 'new'] ← Changed!

2. Best Practices in 2026


# Safe approach with mutable objects
def process_items(items: list) -> list:
    # Work on a copy to avoid side effects
    items_copy = items.copy()
    items_copy.append("processed")
    return items_copy

# Better: Use immutable data when possible
from typing import Tuple

def process_tuple(items: Tuple) -> Tuple:
    return items + ("processed",)

3. When to Choose Immutable vs Mutable

  • Use immutable (tuple, frozenset, NamedTuple) for data that should not change
  • Use mutable (list, dict, set) when you need to modify the collection
  • Pass copies (.copy() or deepcopy()) when you must modify mutable objects
  • Document side effects clearly in function docstrings

Choosing Between Mutable and Immutable Types

Mutable objects, such as lists, dictionaries and sets, can change after they are created. Immutable objects, such as int, float, str, tuple and frozenset, cannot; every operation that looks like a change produces a new object.

Immutability brings safety. An immutable value can be shared between functions without any risk of one changing it for the others, and it can be used as a dictionary key or a set member because its hash never changes. Lists cannot be keys for this reason.

Mutability brings efficiency when you build a collection step by step. Appending to a list in a loop is fast, while concatenating tuples creates a new tuple every time.

A practical rule for data code is to build with mutable types and publish results as immutable ones, for example by returning a tuple or a frozenset from a function that others will reuse.

Worked Example: Keys, Sharing and Hashing

We test which values can be dictionary keys and show how a shared list changes for everyone.

for value in [42, "id", (1, 2), frozenset({3}), [1, 2], {"a": 1}]:
    try:
        hash(value)
        print(type(value).__name__, "hashable")
    except TypeError:
        print(type(value).__name__, "not hashable")

default_tags = ["new"]
a = default_tags
b = default_tags
a.append("sale")
print(b)

frozen = tuple(default_tags)
print(frozen, type(frozen).__name__)

Int, str, tuple and frozenset are hashable, while list and dict are not. Appending through a also changes b, because both names refer to one list. Converting to a tuple produces a value that nobody can change afterwards.

Practical Tips

For records that should not change after creation, consider a named tuple or a frozen dataclass. Both give readable field names and protect against accidental edits.

When a function needs a list as a default argument, use None and create the list inside the function, because a default list is created once and shared between calls.

Check hashability with hash(x) in a quick test when unsure.

Use tuples for fixed records and lists for growing collections.

Common Mistakes

  • Using a list as a dictionary key.
  • Sharing one mutable list between objects by accident.
  • Assuming a tuple is fully immutable when it contains a list.
  • Building large tuples by repeated concatenation in a loop.

Quick Summary

  • Mutable: list, dict, set.
  • Immutable: int, float, str, tuple, frozenset.
  • Only hashable values can be keys.
  • Build mutable, publish immutable.

Conclusion

Understanding immutable vs mutable objects is critical for writing safe and predictable functions. In 2026, the best practice is to prefer immutable data structures whenever possible and to be explicit about mutation when using mutable objects.

Next steps:

  • Review your functions and make mutation behavior explicit

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices