Practical Use Cases and Considerations
Understanding the distinction between mutable and immutable objects in Python has several practical applications and considerations that you should be aware of.
Mutable objects can be modified in-place, which can be more efficient in terms of memory usage. This is particularly useful when working with large datasets or objects that need to be frequently updated. Immutable objects, on the other hand, require creating a new object when the value is changed, which can be less efficient for certain use cases.
import sys
## Example of memory usage for mutable and immutable objects
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
print(f"Size of list: {sys.getsizeof(my_list)} bytes")
print(f"Size of tuple: {sys.getsizeof(my_tuple)} bytes")
Passing by Reference vs. Passing by Value
When you pass a mutable object as an argument to a function, the function can modify the original object. With immutable objects, the function receives a copy of the object, and any changes made within the function do not affect the original object.
def modify_list(lst):
lst.append(4)
my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) ## Output: [1, 2, 3, 4]
def modify_tuple(tup):
tup = (1, 2, 3, 4)
my_tuple = (1, 2, 3)
modify_tuple(my_tuple)
print(my_tuple) ## Output: (1, 2, 3)
Hashability and Dictionary/Set Usage
Immutable objects can be used as keys in dictionaries or as elements in sets, as they have a stable hash value. Mutable objects, however, cannot be used as dictionary keys or set elements, as their hash value can change.
## Using immutable objects as dictionary keys
my_dict = {(1, 2, 3): "value"}
print(my_dict[(1, 2, 3)]) ## Output: "value"
## Using mutable objects as dictionary keys
my_list = [1, 2, 3]
my_dict = {my_list: "value"} ## TypeError: unhashable type: 'list'
By understanding the practical implications of mutable and immutable objects, you can write more efficient and effective code, and make informed decisions about how to structure and manipulate your data in Python.