Python: Mutable, Immutable… everything is object
In the Python language, everything is an object! From ints to dictionaries, every type of data / collection is an object. However, not all objects are treated the same. Some are mutable while others are immutable. What does this mean?
ID and Type
Because everything is an object, when one is created it is assigned an id and its type is selected. Using tools, helpfully named as the functions id() and type() help us to determine whether an object is immutable or mutable. Here is an example of how each of these is used:
>>>name = “holberton”
Mutable vs. Immutable Objects
Now we can get to the main part of the article. To put it simply, mutable objects can change (its state or its contents) while an immutable object cannot. Let’s demonstrate this with an example.
>>> a = [1, 2, 3] #this a list which is mutable
>>> a = 5
[5, 2, 3]
As we can see, changing an item inside the list did not change the object, it has the same id as before. Now lets see another example:
>>> b = "holberton" #this is a string, which is immutable
>>> b = "betty"
Now we see the id has changed, meaning that the original string was discarded and b now points towards a new string.
Why does this matter?
It is important to understand the differences between immutable and mutable data types in order for code to function in the way that is expected. Being careful with these prevents your code from throwing errors, or not setting variables when you think you are.
An example of this is with how mutable vs immutable objects interact with functions.
When a function calls a value, if it is mutable call by reference and immutable call by value. A call by reference means the function can change the value due to it being mutable, so be careful. A call by value means it can’t be changed (if it is tried, instead a copy is made)
Objects in python are fun