Mutable vs Immutable in Python: Key Differences and Usage
mutable objects can be changed after creation, while immutable objects cannot be altered once created. Examples of mutable types include list, dict, and set, whereas int, str, and tuple are immutable.Quick Comparison
Here is a quick side-by-side comparison of mutable and immutable objects in Python.
| Aspect | Mutable | Immutable |
|---|---|---|
| Can be changed after creation? | Yes | No |
| Examples | list, dict, set | int, str, tuple |
| Memory behavior | Same object, changed content | New object created on change |
| Use case | When data needs modification | When data should stay constant |
| Performance | May be slower due to changes | Often faster and safer |
| Hashable? | Usually no | Usually yes |
Key Differences
Mutable objects in Python allow you to change their content without creating a new object. For example, you can add or remove items from a list or update keys in a dict. This flexibility is useful when you want to modify data in place.
On the other hand, immutable objects cannot be changed once created. If you try to modify them, Python creates a new object instead. This behavior applies to types like int, str, and tuple. Immutability helps prevent accidental changes and makes objects safe to use as dictionary keys or set elements.
Because mutable objects can change, they are generally not hashable and cannot be used as keys in dictionaries. Immutable objects are hashable by default, making them suitable for keys. Also, immutable objects often lead to simpler and more predictable code, while mutable objects offer more flexibility.
Code Comparison
Here is how you modify a mutable object like a list by changing its content directly.
my_list = [1, 2, 3] print(f"Original list: {my_list}") my_list.append(4) print(f"Modified list: {my_list}")
Immutable Equivalent
For an immutable object like a tuple, you cannot change it directly. Instead, you create a new tuple with the desired changes.
my_tuple = (1, 2, 3) print(f"Original tuple: {my_tuple}") new_tuple = my_tuple + (4,) print(f"New tuple: {new_tuple}")
When to Use Which
Choose mutable types like list or dict when you need to change data frequently, such as updating a collection of items or caching results.
Choose immutable types like tuple, str, or int when you want to ensure data does not change, which helps avoid bugs and makes your code safer and easier to understand.
Immutability is also important when using objects as dictionary keys or set elements, as mutable objects cannot be used there.