DEV Community

Cover image for Mutable vs Immutable Objects in Python (Explained Simply)
Micheal Angelo
Micheal Angelo

Posted on

Mutable vs Immutable Objects in Python (Explained Simply)

Mutable vs Immutable Objects in Python

I’ve added a simple visual comparing mutable and immutable objects.

Keep it in mind while reading — it helps anchor the mental model.

This post explains a core Python concept that often causes confusion, especially when working with data structures, recursion, and backtracking.


1️⃣ Types of Python Objects

In Python, objects can be broadly classified into two categories based on whether their internal state can change:

  • Mutable objects
  • Immutable objects

Understanding this distinction is critical for writing correct and predictable Python code.


2️⃣ Mutable Objects

Mutable objects are objects whose contents can be changed after creation.

When you modify a mutable object:

  • The same object in memory is updated
  • The memory address does not change

Common Mutable Objects

  • list
  • set
  • dict

Example

a = [1, 2, 3]
a.append(4)
print(a)  # [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Here:

  • a still points to the same list
  • The list’s contents are modified in place

3️⃣ Immutable Objects

Immutable objects are objects whose contents cannot be changed after creation.

Any operation that appears to modify them actually:

  • Creates a new object
  • Assigns a new memory address

Common Immutable Objects

  • int
  • float
  • str
  • tuple
  • frozenset

Example

x = 10
x = x + 1
print(x)  # 11
Enter fullscreen mode Exit fullscreen mode

What happened:

  • 10 was not modified
  • A new integer 11 was created
  • x now points to a new object

4️⃣ Why This Difference Matters

This distinction affects:

  • Function arguments
  • Recursion and backtracking
  • Shared references
  • Unexpected side effects

Example: Function Behavior

def add_item(lst):
    lst.append(100)

nums = [1, 2, 3]
add_item(nums)
print(nums)  # [1, 2, 3, 100]
Enter fullscreen mode Exit fullscreen mode

The list changed outside the function because it is mutable.


5️⃣ Mental Model (Remember This)

Mutable objects change in place

Immutable objects create new values

If you remember this, most bugs around this topic disappear.


TL;DR

  • Mutable objects can be changed after creation
  • Immutable objects cannot
  • Lists, sets, dicts → mutable
  • Ints, strings, tuples → immutable
  • Mutability affects function behavior and bugs

Understanding mutability early will save you hours of debugging later.

Top comments (0)