Course contentsShow
← Python
Lesson 24 of 1,0601. Foundations and EnvironmentFree lesson

Handling Mutable and Immutable Object Types

You will categorize data types as mutable or immutable to predict how operations modify objects in place or create new ones.

Handling Mutable and Immutable Object Types

In this lesson, you will learn how to distinguish between objects that can change and those that cannot, allowing you to predict how Python handles your data in memory.

The Two Worlds of Data

Every object in Python falls into one of two categories based on whether its value can be modified after it is created: mutable or immutable.

  • Immutable objects are "locked." Once you create them, their value can never change. If you try to modify them, Python actually creates a brand new object in memory and updates your variable to point to that new location. Common immutable types include int, float, str, and tuple.
  • Mutable objects are "flexible." You can change their internal contents without creating a new object. The memory address (the "box" the object lives in) remains exactly the same while the data inside the box changes. Common mutable types include list.

Seeing it in Action

Let’s look at the difference when we "change" a value:

# Immutable example: A string
name = "Alice"
print(id(name))  # Displays a memory address
name = "Bob"
print(id(name))  # Displays a DIFFERENT memory address!

# Mutable example: A list
my_list = [1, 2, 3]
print(id(my_list))  # Displays a memory address
my_list.append(4)
print(id(my_list))  # Displays the SAME memory address!

In the string example, "Alice" is immutable. We didn't change the string; we abandoned the "Alice" object and pointed name to a completely new "Bob" object.

In the list example, the list is mutable. When we used .append(), Python modified the existing list object in its original spot in memory. Because the list is mutable, the object identity (the ID) stayed the same throughout the process.

Understanding this distinction helps you avoid bugs where you might accidentally change an object that you meant to keep in its original state, or wonder why a variable you thought was updated didn't reflect changes elsewhere in your code.

Key Takeaway: Immutable objects create a new object when modified, while mutable objects allow you to change their contents while keeping the same object identity.