What is the key difference between a mutable and an immutable object? This question is answered in this lesson of the course.
Mutable Objects vs Immutable Objects in Python
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.
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.
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.
Become a Member to join the conversation.