Python Mastery – From Basics to Brilliance / Python Fundamentals

Mutable and Immutable Objects

πŸ”„ Mutable and Immutable Objects

In Python, objects are either mutable or immutable depending on whether their contents can be changed after they are created.

🟒 Mutable Objects

Mutable objects can be changed after creation.

Common mutable types:

list
set
dictionary

Example:

numbers = [1, 2, 3]

numbers[0] = 10

print(numbers) # [10, 2, 3]

The same list was changed.


πŸ”΄ Immutable Objects

Immutable objects cannot be changed after creation.

Common immutable types:

int
float
bool
str
tuple

Example:

x = 10

x = 20

Here, the original 10 is not changed. Instead, x is made to refer to a new integer object containing 20.

Strings work similarly:

name = "Python"

name[0] = "J"   # ❌ Error

A string cannot be modified directly.


βš–οΈ Mutable vs Immutable

Mutable 🟒

Immutable πŸ”΄

Can be changed after creation

Cannot be changed after creation

list

int

set

float

dict

bool

str

tuple