Mutable VS Immutable Objects In Python - Nerd Platoon Mutable VS Immutable Objects In Python - Nerd Platoon

Every built-in data type in Python is actually a class, so Python treats every variable storing a value as an object of that class. Similarly, every object has an identifier, a type, and a value. Also, Python objects are either Mutable or Immutable. In simple terms, mutable data objects are those objects which can have values added, removed, or changed. However, immutable data objects cannot have any updates in their values.

Some common examples of built-in mutable data types in Python are list, set, dictionary, and classes. Similarly, immutable data types in Python include integer, float, decimal, boolean, string, tuple, etc.

Let us see some examples to understand this better.

>>> company = ‘Nerd Platoon’

>>> company[ 4] = ‘-‘

Traceback (most recent call last):

File “<stdin>”, line 1, in <module>

TypeError: ‘str’ object does not support item assignment

We get an error here mentioning that string does not support item assignment. So, we can update or “mutate” a string object by using string operations like slicing and concatenation to build a purely new string by copying its parts from the previous string object.

>>> company = ‘Nerd Platoon’

>>> new_company_name = company[:4] + ‘-‘ + company[5:]

>>> new_company_name


>>> company

‘Nerd Platoon’

So, we can see here that the actual string object stored in the “company” variable does not change as strings are immutable objects.

However, if we consider a list data type, it does have methods such as append(), insert(), remove(), pop(), and extend(), which allows for changes to take place in the actual list object itself. Hence, a list object is considered mutable.

Let us see this in action.

>>> services_offered = [‘Web Development’, ‘SEO’, ‘Mobile App Development’]

>>> services_offered.append(‘Data Analytics’)

>>> services_offered.append(‘Machine Learning’)

>>> services_offered.append(‘Digital Marketing’)

>>> services_offered

[‘Web Development’, ‘SEO’, ‘Mobile App Development’, ‘Data Analytics’, ‘Machine Learning’, ‘Digital Marketing’]

>>> del services_offered[4]

>>> services_offered

[‘Web Development’, ‘SEO’, ‘Mobile App Development’, ‘Data Analytics’, ‘Digital Marketing’]

So, based on these examples, we can come to a conclusion that we use mutable data types, mainly when we want dynamic changes to the object itself. On the other hand, we use immutable data types when we want to store something static and predefined.

I hope this blog post clears out the main concepts of mutability and immutability in Python. So I would leave you all with a question: Would you store the days of a week using a mutable data type (list) or an immutable data type (tuple)? Please put your thoughts in the comment below.

Congrats for making it to the end!