Understand Mutable vs. Immutable objects in Python

Will Button
InstructorWill Button
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 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.

egghead
egghead
~ 5 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today