Understand Mutable vs. Immutable objects in Python

Will Button
InstructorWill Button

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

In this lesson, you will learn what mutable and immutable objects are, and the difference between them. This understanding will help you determine when objects can be modified in place, and when new objects must be created.

Instructor: Everything in Python has an ID and a value. If I create a list, I can check the ID of that list using the ID function.

If I pinned the number three to that list, I can check the ID of it again, and the same ID is returned. This means that the list object in Python is mutable, and the same is true for dictionaries.

Immutable objects, however, can't be altered. If I create A and set it equal to four, we can check the ID of A, and then if I say A is equal to A + 1 and then check the ID of A again, you can see that we have a new ID, so the new variable was created instead of just modifying the existing one.

Things that are immutable in Python are strings, integers, and tuples. Let's take a look at a string real quick, if we check the ID of our phrase. I can modify the value of it from hello to world and check the ID of it again, and you can see that we have a new ID.

While that may seem a little strange since we're referring to the same variable, the good news is that you don't have to track the ID. Python does that for you.