Mutable Objects vs Immutable Objects in Python
What is the key difference between a mutable and an immutable object? This question is answered in this lesson of the course.
Check out Python’s Mutable vs Immutable Types: What’s the Difference? to learn more.
00:00 All right, so let’s get started. To demonstrate what immutable or immutability means, I’m going to create a mutable object and then an immutable object, and then I’m going to show you the difference. For a mutable object, which means an object that can be freely modified, an example would be to create a simple list.
00:21
I’m going to create a list and I’m going to put some values into it. Let’s go with ['a', 'b', 'c']
. And with a mutable object, I can freely modify this object. So I can go in here and I can say “Let’s change the value at index 1
.” And when we look at a mutable object, you can see here that this mutation was applied.
00:47
We modified the contents of this object. Now, with an immutable object we can’t do that. An example for an immutable object would be a tuple here. I’m going to create a tuple with the same contents, and now when we try to apply the same modification, we’re getting a TypeError: 'tuple' object does not support item assignment
.
01:10 And that’s really the key difference. A mutable object can be freely modified and an immutable object can’t.
Become a Member to join the conversation.