Skip to main content

Mutable vs Immutable in Python: Understanding Objects and References

MY LEARNING JOURNEY · 05

Updated 7 min readMarkdown
Part of seriesPython Learning Journey

Learning Python with Chai aur Code, one video at a time.

Learning source: Chai aur Code — Python Video 5

1. What Do Mutable and Immutable Mean?

Let's start with the literal meaning of these two words:

  • Mutable: Something that can be changed.
  • Immutable: Something that cannot be changed.

In Python, these terms describe whether an object can be modified after it has been created.

For example:

  • Lists are mutable.
  • Dictionaries are mutable.
  • Sets are mutable.
  • Integers are immutable.
  • Floats are immutable.
  • Strings are immutable.
  • Tuples are immutable.

But this brings up an interesting question:

If strings are immutable, why can I change the value of a variable containing a string?

Before answering that, we need to understand something important about Python.

2. Is Everything an Object in Python?

According to Python, everything is an object.

But what exactly does that mean?

When we say everything, we're referring to values and the things we work with in Python, such as:

  • Integers
  • Strings
  • Lists
  • Dictionaries
  • Functions
  • Classes
  • Modules

These are all objects in Python.

For example:

user = "ad"
age = 20
numbers = [10, 20, 30]

Here:

  • "ad" is a string object.
  • 20 is an integer object.
  • [10, 20, 30] is a list object.

Even functions and classes are objects in Python.

This is why Python is often described as an object-based language where values have types and objects have identities.

One thing I found interesting is that variables in Python don't work exactly like labelled boxes that permanently store values.

Instead, a variable name refers to an object.

And that brings us to memory references.

3. What Is a Memory Reference?

Let's take the example:

user = "ad"

When Python executes this statement:

  1. A string object containing "ad" is available.
  2. The name user is bound to that object.

We can think of it like this:

user ───────► "ad"
              String object

The arrow represents the reference between the variable name and the object.

Now, let's change the variable:

user = "ab"

What happens?

user ───────► "ab"
              String object

The name user now refers to the "ab" string object instead of the "ad" object.

But wait!

Didn't we just change a string? Aren't strings immutable?

This is where the difference between changing an object and reassigning a variable becomes important.

4. If Strings Are Immutable, Why Can We Change Their Values?

Remember:

Immutable means that the object itself cannot be modified after creation. It does not mean that a variable cannot refer to a different object.

Let's understand this with our example:

user = "ad"
user = "ab"

We didn't modify the original "ad" string object.

Instead, we created or referred to another string object, "ab", and reassigned the name user to it.

The important distinction is:

  • Modifying an object means changing the existing object.
  • Reassigning a variable means making that variable refer to another object.

Since strings are immutable, we cannot modify the existing string object.

But we can absolutely reassign the variable to another string.

That's why this works without violating the immutability of strings.

5. What Happens to the Original "ad" Object?

Now another question came to mind:

If user no longer refers to "ad", what happens to the original object?

Let's look at the sequence:

user = "ad"
user = "ab"

Initially:

user ───────► "ad"

After reassignment:

user ───────► "ab"

"ad"  (no longer referred to by user)

If no other references to "ad" exist, that object may become eligible for garbage collection.

What Is Garbage Collection?

Garbage collection is the process of identifying and reclaiming memory occupied by objects that are no longer needed.

Python manages memory automatically, so we generally don't have to manually delete objects just because we no longer need them.

However, an important clarification:

An object becoming unreachable doesn't necessarily mean it gets deleted immediately.

The exact memory-management behaviour depends on the Python implementation.

For example, CPython primarily uses reference counting along with a garbage collector for certain reference cycles.

So, we shouldn't imagine garbage collection as something that instantly deletes every object as soon as we stop referring to it.

6. What Happens When Two Variables Refer to the Same Object?

Now let's consider another example.

x = 10
y = x

Here, both x and y refer to the same integer object.

We can visualize it like this:

       ┌────────► 10
x ─────┤          Integer object
       │
y ─────┘

Now, let's check their values:

print(x)
print(y)

Output:

10
10

Both variables show 10 because both refer to the same object.

But what happens when we change x?

x = 15

Now:

x ─────────► 15

y ─────────► 10

If we print them:

print(x)
print(y)

Output:

15
10

Why?

Because we didn't modify the integer object 10.

We simply reassigned x to refer to another integer object, 15.

The reference held by y remained unchanged.

This is the same idea we saw with strings.

And since integers are immutable, this behaviour makes perfect sense.

7. Does This Work Only in the Python Shell?

No!

This behaviour isn't specific to the Python shell.

The Python shell is simply an interactive environment where we can experiment with code and immediately see the results.

The underlying behaviour of objects, references, mutability, and reassignment remains the same when we run Python files.

For example, the following code:

x = 10
y = x

x = 15

print(x)
print(y)

Will produce:

15
10

Whether we execute it in the Python shell or save it inside a .py file and run that file, the result is the same.

The working doesn't change. Only the way we execute the code changes.

8. My Key Takeaways

Here's what I understood from this topic:

  1. Mutable objects can be modified after creation.
  2. Immutable objects cannot be modified after creation.
  3. In Python, values are objects, including integers, strings, lists, and functions.
  4. Variable names refer to objects rather than permanently storing values in separate boxes.
  5. Memory references help explain which object a variable name refers to.
  6. Reassigning a variable doesn't modify the original object.
  7. Objects that are no longer reachable can become eligible for garbage collection.
  8. Two variables can refer to the same object.
  9. Python's behaviour regarding objects and references remains the same in the shell and in regular Python files.

Final Thoughts

Initially, I was confused about how strings could be immutable when I could easily change the value assigned to a string variable.

But after understanding the difference between modifying an object and reassigning a variable, things started making sense.

The same idea also helped me understand why changing x doesn't automatically change y, even when both variables initially refer to the same integer object.

One thing I'm taking away from this topic is that we should distinguish between the variable name and the object it refers to.

That small distinction makes several Python behaviours much easier to understand.


This is part of my Python learning journey, where I document what I understand from each Chai aur Code lecture, the questions I encounter, and the concepts I explore along the way.

Did I misunderstand anything about objects, references, or garbage collection? I'd love to hear your explanations and corrections in the comments.

About the author

  • As a newbie, learning Python, bit by bit and error by error. I write about the things I learn, the queries I have and things I finally understand. If you’re learning as well, let’s do this together!

No comments yet. Be the first to comment.

Python Learning Journey

Part 5 of 5

I'm documenting my journey of learning Python through Chai aur Code, one video at a time. I'll share what I understand, the questions I encounter, the concepts I explore with AI, and the code I experiment with along the way. My goal is to learn by questioning, explaining concepts in my own words, and sharing the journey publicly. I'm a beginner, and I'm always open to suggestions that can help me learn better.

Start from the beginningHow I Started Learning Python with Chai aur Code — And the Learning Habit That's Helping Me MostMY LEARNING JOURNEY · 01