Immutable vs Mutable Objects
In this lesson, you’ll learn about the two types of objects in Python:
- A mutable object can have its value changed after it has been created.
- An immutable object can’t be modified.
Understanding this difference is the first key to navigating the landscape of pointers in Python.
00:13 after it’s been created. The object in memory can be edited directly instead of having to create a new copy of the object with the desired changes. Take, for example, the list. You can create a list of elements and then, later on, change one of them without having to recreate the whole list in memory.
00:37 This is not the case for other types of objects, for example, the Python string. The string type is immutable because, in order to mutate it, Python will have to create a whole new string object under the hood.
00:52 This is why many string functions built into the standard library return a copy of the modified string. Why the string is immutable, and the list mutable, is a design choice that’s beyond the scope of this course.
01:21 As you can see, a bunch of types are immutable. The only ones capable of mutation after they’ve been created are the list, set, and dictionary. To show this in action, we can use the Python interactive shell.
If you look carefully at the end of the address, you can see that it’s different. That’s because the integer type is immutable. Python wasn’t able to change the value of
x directly, so it created a new space in memory for a new
x value of 6, then changed our variable to point to that space in memory.
This applies to strings too, because they’re also an immutable type. I’ll start by defining a new string called
name. And now, if we try to change the first character like this, we’ll get a
03:21 There’s the new integer. And if I get its id, you’ll see that it’s the same as it was before. That’s because the list type is mutable, so Python could change it without having to create a whole new list object in memory. In the next video, you’ll learn more about how Python variables work under the hood.
Become a Member to join the conversation.