0
0
PythonConceptBeginner · 3 min read

Mutable and Immutable in Python: What They Are and How They Work

In Python, mutable objects can be changed after creation, while immutable objects cannot be altered once created. Examples of mutable types include list and dict, and immutable types include int, str, and tuple.
⚙️

How It Works

Think of mutable objects like a whiteboard where you can erase and write new things anytime. You can change their content without creating a new object. Immutable objects are like a printed book page; once printed, you cannot change the words on that page without printing a new one.

In Python, this means mutable objects allow changes to their data after they are created, while immutable objects do not allow any changes. When you try to change an immutable object, Python creates a new object instead.

💻

Example

This example shows how a list (mutable) can be changed, but a string (immutable) cannot be changed directly.

python
my_list = [1, 2, 3]
my_list[0] = 10

my_string = "hello"
try:
    my_string[0] = "H"
except TypeError as e:
    error_message = str(e)

print("Modified list:", my_list)
print("Error when changing string:", error_message)
Output
Modified list: [10, 2, 3] Error when changing string: 'str' object does not support item assignment
🎯

When to Use

Use mutable objects when you need to change data frequently, like updating a list of tasks or modifying a dictionary of settings. Mutable types are efficient for such cases because you can update them without creating new objects.

Use immutable objects when you want to ensure data does not change, such as keys in dictionaries or fixed values like dates or names. Immutable objects help avoid accidental changes and make your code safer and easier to understand.

Key Points

  • Mutable objects can be changed after creation; immutable objects cannot.
  • Lists and dictionaries are common mutable types.
  • Strings, integers, and tuples are common immutable types.
  • Trying to change an immutable object causes Python to raise an error.
  • Choosing mutable or immutable depends on whether you want data to be changeable or fixed.

Key Takeaways

Mutable objects can be changed after creation; immutable objects cannot.
Lists and dictionaries are mutable; strings and tuples are immutable.
Use mutable types for data that changes often and immutable types for fixed data.
Trying to modify an immutable object raises an error or creates a new object.
Understanding mutability helps write safer and more efficient Python code.