Understanding Mutable and Immutable Types in Python
In Python, data types can be classified into mutable and immutable based on whether their content can be changed after creation. This concept is fundamental for writing correct and efficient code.
What Are Mutable Types?
Mutable types are objects whose values can be changed after they are created. This means you can modify, add, or remove elements without creating a new object.
Common Mutable Types:
list
dict
(dictionary)set
bytearray
Example:
my_list = [1, 2, 3]
my_list[0] = 10 # Modify the first element
print(my_list) # Output: [10, 2, 3]
In this example, the list is modified in place.
What Are Immutable Types?
Immutable types are objects whose values cannot be changed once created. Any modification results in the creation of a new object.
Common Immutable Types:
int
float
bool
str
(string)tuple
frozenset
Example:
my_str = "hello"
new_str = my_str.upper() # Returns a new string, original unchanged
print(my_str) # Output: hello
print(new_str) # Output: HELLO
Strings cannot be changed in place; operations produce new strings.
Why Does Mutability Matter?
- Performance
Modifying mutable objects can be faster since it avoids creating new objects. - Function Behavior
Mutable objects passed into functions can be changed inside the function, affecting the original object (pass-by-reference behavior). - Hashing and Dictionary Keys
Only immutable objects can be used as dictionary keys or set elements because their hash value must remain constant.
Comments are closed.