Mutable vs Immutable Data Types
In Python, every value we store in a variable has a data type. These data types are divided into two categories: mutable and immutable, depending on whether their values can be changed after creation.
Mutable Data Types
Mutable means changeable. If a data type is mutable, it means you can add, remove, or modify its elements without creating a new object in memory. When you change a mutable object, its memory address (ID) stays the same.
Common mutable data types:
- list
- dict
- set
- bytearray
Example:
# Example of a mutable data type (list)
fruits = ["apple", "banana", "cherry"]
print(id(fruits)) # Memory address before modification
fruits.append("mango") # Adding a new item
print(fruits)
print(id(fruits)) # Same memory address → same objectOutput:
140394891456640
['apple', 'banana', 'cherry', 'mango']
140394891456640Explanation: The memory address remains the same even after adding a new element. This means the original list was changed directly, not replaced.
Immutable Data Types
Immutable means unchangeable. If a data type is immutable, it means its value cannot be changed once created. If you try to modify it, Python will create a new object instead of changing the existing one. As a result, its memory address (ID) changes.
Common immutable data types:
- int
- float
- complex
- str
- tuple
- bool
- bytes
Example:
# Example of an immutable data type (string)
name = "Harry"
print(id(name)) # Memory address before modification
name = name + " Potter" # Concatenating creates a new string
print(name)
print(id(name)) # Different memory address → new object createdOutput:
140394891763824
Harry Potter
140394891765008Explanation:
Here, a new string "Harry Potter" was created in memory instead of modifying the old one.
That’s why the memory address changed.
Summary Table
| Category | Data Type(s) | Mutable | Immutable |
|---|---|---|---|
| Numeric | int, float, complex | No | Yes |
| Text | str | No | Yes |
| Boolean | bool | No | Yes |
| Sequence | list, tuple, range | Yes (list) | Yes (tuple, range) |
| Mapped | dict | Yes | No |
| Set | set | Yes | No |
| Binary | bytes, bytearray, memoryview | Yes (bytearray) | Yes (bytes) |
| None Type | NoneType | No | Yes |
Notes
- Mutable means the value can change without creating a new object.
- Immutable means the value cannot change; a new object is created when modified.
- Mutable objects are useful when you need to update data frequently (like lists or dictionaries).
- Immutable objects help prevent accidental changes and make your code more predictable.