Python: Mutable, Immutable… everything is object

Colorful clay shaped into objects and creatures

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?

A scene from Spongebob, characters are labeled after data types. A lady exasperatedly asks if there are any other objects.
A scene from Spongebob, characters are labeled after data types. A lady exasperatedly asks if there are any other objects.

ID and Type

>>>name = “holberton”
>>>id(name)
183625186720
>>>type(name)
<class: 'string'>

Mutable vs. Immutable Objects

>>> a = [1, 2, 3] #this a list which is mutable
>>> id(a)
102983547029
>>> a[0] = 5
>>> print(a)
[5, 2, 3]
>>> id(a)
102983547029

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
>>> id(b)
103748392048
>>> b = "betty"
>>> id(b)
103749829789

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?

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