Python: Mutable vs. Immutable

In Python, data types can be categorized as either mutable or immutable based on whether their values can be changed after creation. This distinction has important implications for how variables and objects behave.

Mutable in Python

Mutable objects are those whose values can be modified after they are created. This means you can change their internal state without changing their identity. Examples of mutable objects in Python include lists, dictionaries, and sets.

my_list = [1, 2, 3] my_list[0] = 10 # Modifying the first element print(my_list) # Output: [10, 2, 3]

In this example, the list my_list is mutable, so you can modify its elements without creating a new list.

Immutable in Python

Immutable objects, on the other hand, cannot be changed after they are created. When you want to change the value of an immutable object, you actually create a new object with the updated value. Examples of immutable objects in Python include integers, strings, and tuples.

my_string = "Hello" new_string = my_string.upper() # Creating a new string with uppercase letters print(my_string) # Output: "Hello" print(new_string) # Output: "HELLO"

In this example, the method upper() doesn't modify the original string but instead creates a new string with the uppercase characters.

Mutable vs. Immutable in Python

  1. Mutable objects can be modified in place, while immutable objects cannot.
  2. When you modify a mutable object, other references to the same object will see the changes. For immutable objects, new objects are created when changes are made.

It's important to be aware of mutability, as it affects how objects are used and shared in your code. Mutable objects can lead to unexpected behavior if not handled properly, especially when they are shared among different parts of your code.

For instance, when passing mutable objects like lists to functions, modifications made inside the function can affect the original list, whereas passing immutable objects will not have this effect.

def modify_list(lst): lst.append(4) my_list = [1, 2, 3] modify_list(my_list) print(my_list) # Output: [1, 2, 3, 4]

Conclusion

Mutable objects can be changed after creation, while immutable objects cannot. Understanding this distinction is crucial for writing correct and predictable Python code.