Mutability and Immutability in Python

Mutability, in the context of software, is related to the ability of a certain structure to be modified at will.

You can add, remove, or simply change/update items.

In short, mutable objects allow modification after their creation.

Immutability, of course, is the exact opposite, you can’t modify immutable objects after their creation.

Just for your reference, here is a list of some mutable and immutable objects:

  • list, dict, and set are Mutable objects
  • int, float, complex, string, and tuple are Immutable objects

As stated, int is immutable, but how so if you can change a variable from age = 2 to age = 4?

When we change the value of age, the variable age is changed, the value 2 is not modified.

We can use the id() function to check that. This function gives you the object’s location in memory.

Let’s understand mutability with an example.

First, we assign 4 to a and then a to b. Now both a and b are equal to 4.

As we can use, the id() function shows that a, b, and the value object 4 all point to the same location in memory, in my case, 4526707936 (it will be a different location in your computer).

When we check id(a) == id(b), the return is True.

After that, we change the value of a to 7.

Notice how a now points to a new location 4526708032 while b and 4 still point to 4526707936.

You see, the integer 4 is immutable, it doesn’t change.

>>> a = 4
>>> b = a
>>> b
4
>>> id(4)
4526707936
>>> id(a)
4526707936
>>> id(b)
4526707936
>>> id(a) == id(b)
True
>>> a = 7
>>> id(a)
4526708032
>>> id(b)
4526707936
>>> id(a) == id(b)
False
>>> a
7
>>> b
4
>>> id(4)
4526707936
>>> id(a) == id(4)
False
>>> id(b) == id(4)
True

Now, if we try to do the same with a list, which is mutable, we will notice a difference.

We initialize car_brands with ['bmw', 'ferrari', 'mclaren'], then we assign car_brands to brands_list.

We check that both lists point to the same location in memory.

Then we remove ‘ferrari’ from the list and check and compare memory locations again, and… it is still the same!

>>> car_brands = ['bmw', 'ferrari', 'mclaren']
>>> brands_list = car_brands
>>> id(car_brands)
4529435984
>>> id(brands_list)
4529435984
>>> id(car_brands) == id(brands_list)
True
>>> car_brands.remove('ferrari')
>>> car_brands
['bmw', 'mclaren']
>>> brands_list
['bmw', 'mclaren']
>>> id(car_brands)
4529435984
>>> id(brands_list)
4529435984
>>> id(car_brands) == id(brands_list)
True

Both lists point to the same location in memory, and when ‘ferrari’ was removed, bith car_brands and brands_list were affected.

Mutability is an important concept when working with different data structures.

You can refer to How to choose a Data Structure in Python to understand when to use each data structure now that you know the concept of Mutability.