What does Mutability mean in Python?
Mutability is a critical concept to successfully understand how to work with data types and data structures. Let's see what does it mean.
Mutability is about whether we can change an object once it has been created. For example, consider a list of fruits that we decide to modify adding a new item at the end:
fruits = ["Apple", "Banana", "Watermelon", "Cherry"] fruits.append("Peach") print(fruits) ## Output: ['Apple', 'Banana', 'Watermelon', 'Cherry', 'Peach']
As you can see, a list is a mutable data structure. If you have a data structure that can't be changed at least you create a new object (like a string), then we call it "immutable".
In case we try to modify an immutable object, the result will be an error. For example, here we are trying to use the method
.append to add a second value to the variable
user = "Charles" user.append("Anna") print(user)
Since strings objects are no compatible with
.append, and are also immutable, the output would be:
AttributeError: 'str' object has no attribute 'append'
So, how do you correct or change the value of an immutable object? As we said before, you would need to create a new object to replace the previous variable. In this case:
user = "Charles" user = "Anna" print(user) ## Output: Anna