In Python, the distinction between mutable and immutable data types is fundamental to how the language handles memory and variable assignments. Here’s a breakdown:
Mutable Data Types
Mutable data types allow modifications after their creation. You can change their content, such as adding, removing, or updating elements, without creating a new object.
Examples of Mutable Data Types
- Lists:
my_list = [1, 2, 3] my_list.append(4) # Modifies the original list print(my_list) # Output: [1, 2, 3, 4]
- Dictionaries:
my_dict = {"key1": "value1", "key2": "value2"} my_dict["key3"] = "value3" # Adds a new key-value pair print(my_dict) # Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
- Sets:
my_set = {1, 2, 3} my_set.add(4) # Modifies the original set print(my_set) # Output: {1, 2, 3, 4}
Key Characteristics of Mutables:
- Changes affect the original object.
- Mutable objects can lead to unexpected side effects when shared across variables or passed as arguments.
Immutable Data Types
Immutable data types cannot be changed after creation. Any operation that tries to modify an immutable object creates a new object instead.
Examples of Immutable Data Types
- Strings:
my_string = "hello" new_string = my_string + " world" # Creates a new string print(my_string) # Output: hello print(new_string) # Output: hello world
- Tuples:
my_tuple = (1, 2, 3) # my_tuple[0] = 0 # This will raise a TypeError
- Numbers (integers, floats, etc.):
num = 10 num += 5 # Creates a new integer object print(num) # Output: 15
- Frozensets:
my_frozenset = frozenset([1, 2, 3]) # my_frozenset.add(4) # This will raise an AttributeError
Key Characteristics of Immutables:
- Content cannot be changed once created.
- Immutable objects are thread-safe and often used as dictionary keys or set elements because they guarantee hash consistency.
Behavior of Variables with Mutables and Immutables
- Mutables: Assigning a mutable object to another variable creates a reference to the same object, not a copy.
list1 = [1, 2, 3] list2 = list1 # Both variables reference the same list list2.append(4) print(list1) # Output: [1, 2, 3, 4]
- Immutables: Assigning an immutable object to another variable creates a new object when modified.
a = 10 b = a # Both reference the same value initially b += 5 # Creates a new integer object for b print(a) # Output: 10 print(b) # Output: 15
Why Does This Matter?
Understanding mutability helps in:
- Avoiding unintended side effects when passing mutable objects to functions.
- Writing efficient, thread-safe code.
- Correctly managing memory and references in Python.