🐍 Python Q9 / 100

What is mutable and immutable in Python?

AI-Powered Answer ✓ Answered

In Python, the distinction between mutable and immutable data types is fundamental to understanding how variables behave and how memory is managed. It determines whether the value of an object can be changed after it has been created.

Understanding Mutability

Mutability refers to the ability of an object to be changed after it is created. If an object is mutable, its state can be altered without creating a new object. If an object is immutable, its state cannot be changed once it's created; any operation that appears to modify it actually creates a new object.

Mutable Types

  • List
  • Dictionary
  • Set
  • Byte Array

Mutable objects can be modified in-place. This means that if you have a variable referencing a mutable object, you can change the content of that object directly without assigning a new object to the variable. All references to that object will see the updated value.

python
my_list = [1, 2, 3]
print(f"Original list: {my_list}")
my_list.append(4)
print(f"Modified list: {my_list}")

# Demonstrating shared reference
another_list = my_list
another_list.append(5)
print(f"Original list after shared modification: {my_list}")
print(f"Another list: {another_list}")

Immutable Types

  • Integer
  • Float
  • String
  • Tuple
  • Frozenset
  • Bytes

Immutable objects cannot be changed after creation. Any operation that seems to modify an immutable object, such as concatenating strings or adding to numbers, actually results in the creation of a *new* object with the updated value, and the variable is then re-assigned to this new object. The original object remains unchanged in memory (until garbage collected).

python
my_string = "Hello"
print(f"Original string: {my_string}")
print(f"ID of original string: {id(my_string)}")

my_string = my_string + " World"
print(f"Modified string (new object): {my_string}")
print(f"ID of new string: {id(my_string)}")

my_tuple = (1, 2, 3)
# my_tuple.append(4) # This would raise an AttributeError

Why Does it Matter?

Understanding mutability is crucial for several reasons: - Function Arguments: When mutable objects are passed to functions, changes made inside the function persist outside. Immutable objects passed to functions cannot be changed by the function itself (only re-assigned within the function's scope). - Dictionary Keys and Set Elements: Only immutable objects can be used as keys in dictionaries or elements in sets, because their hash value must remain constant throughout their lifetime. - Concurrency: Immutable objects are inherently thread-safe as their state cannot change, simplifying concurrent programming. - Memory Efficiency: Repeated modifications to immutable objects can lead to creation of many new objects, potentially impacting performance and memory usage if not handled carefully.

FeatureMutableImmutable
Change after creationYesNo
ID remains same after changeYesNo (new object created)
Used as dict key/set elementNoYes
ExamplesList, Dict, SetInt, Float, String, Tuple