What are mutable and immutable data types in Python?
Python data types behave differently when modified, which can confuse new learners. Some objects change in place, while others create new objects in memory.
What is the difference between mutable and immutable data types in Python, which data types fall into each category, and why is this distinction important?
What are mutable and immutable data types in Python?
In Python, data types are classified as mutable or immutable based on whether their value can be changed after creation. Understanding this is important because it affects how variables, memory, and functions behave in Python programs.
✅ Immutable Data Types
Immutable objects cannot be changed after they are created. If you try to modify them, Python creates a new object instead of changing the existing one.
Common immutable types:
-
int(integer) -
float(decimal numbers) -
str(string) -
tuple -
frozenset -
bool
Example:
x = 10
print(id(x)) # memory address
x = x + 5 # modifies x
print(id(x)) # new memory address
-
The original object
10is not changed -
xnow points to a new object15
Immutable string example:
name = "Mohi"
name[0] = "A" # ❌ TypeError
Strings cannot be changed, so Python raises an error.
✅ Mutable Data Types
Mutable objects can be changed in place without creating a new object. This allows you to modify data without changing the memory reference.
Common mutable types:
-
list -
dict -
set -
bytearray
Example:
numbers = [1, 2, 3]
print(id(numbers)) # memory address
numbers.append(4) # modify the list
print(numbers) # [1, 2, 3, 4]
print(id(numbers)) # same memory address
-
The list is modified in place
-
The memory location stays the same
✅ Key Differences
| Feature | Mutable | Immutable |
|---|---|---|
| Can it be changed? | Yes | No |
| Memory | Same memory reference | New memory created |
| Examples | list, dict, set | int, float, str, tuple |
🔑 Why it matters
-
Function behavior:
Mutable objects can be changed inside functions, immutable objects cannot. -
Performance:
Immutable objects are generally faster and safer for constant values. -
Data integrity:
Use immutable objects when you want to protect data from accidental changes.
✅ Real-life analogy
-
Immutable: A printed book – you cannot change the text; you must write a new book to modify it.
-
Mutable: A whiteboard – you can erase and write over it as many times as needed.
Understanding mutable vs immutable helps you avoid bugs, manage memory efficiently, and write better Python code.