Python – Mutable vs Immutable

I don’t want this to be a very big article or tutorial. This is just a brief discussion about what is this Mutable – Immutable business in Python?

By definition, Mute means refraining from speech. In the Python world, it means refraining from responding. So, whenever you can force your change on the objects and they accept the changes (sounds gory though!) they are called the Mutable objects, the object that can be muted. On the opposite side, there are objects in Python which will resist and revolt against the changes you are forcing on them. These are Immutable objects, the objects which cannot be muted. The ones which will not accept the change and will send a clear response of rejection.

Also, note that we are not talking about replacing or appending stuff here. We are talking about in place editing of the objects.

Ok, this all sounds a bit vague.. Let’s quickly jump to an example before we all get crazy!

Let’s take a look at the following code

list_1 = [1,2,3] 
tuple_1 = (1,2,3)

list_1[0] = 5
tuple_1[0] = 5

Please try to debug it.. you will get following result

Mutable vs Immutable Replacing an item in List vs Tuple

“Yes… I use Visual Studio Code for Python debugging. I have created a tutorial to setup Visual Studio Code for Python debug. But, that’s not the topic of this tutorial.”

Take a look at the error message which says “tuple’ object does not support item assignment” So, in simple terms what Python is saying that you cannot change in place or replace an item in the tuple because it is Immutable ie it will not accept change within the object.

Wait! What about the list? No error for it?… No! Because the List is a mutable object which means it will accept the change within itsel.

Let’s take another example. Here I have used a function to explain how Mutable and Immutable objects react?

def fun1(d):
    d[5] = "Jaipur"

def fun2(d,i):
    d[i] = "New City"

def fun3(s):
    s += " Additional string!"

dict_1 = {1:"Pune", 2:"Mumbai", 3:"Chennai", 4:"Delhi"}
str_1 = "This is a sample string"

print(dict_1) # -> {1: 'Pune', 2: 'Mumbai', 3: 'Chennai', 4: 'Delhi'}
fun1(dict_1)
print(dict_1) # -> {1: 'Pune', 2: 'Mumbai', 3: 'Chennai', 4: 'Delhi', 5: 'Jaipur'}

print(dict_1) # -> {1: 'Pune', 2: 'Mumbai', 3: 'Chennai', 4: 'Delhi', 5: 'Jaipur'}
fun2(dict_1,3)
print(dict_1) # -> {1: 'Pune', 2: 'Mumbai', 3: 'New City', 4: 'Delhi', 5: 'Jaipur'}

print(str_1) # -> This is a sample string
fun3(str_1)
print(str_1) # -> This is a sample string

From this example, it has become very clear that the Immutable string did not change but the Mutable dictionary did. This is the difference between Mutable and Immutable objects.

Example of Mutable and Immutable Objects

ObjectsMutableImmutable
List
Dict
Set
Bytearray
User defined class objects
Int
Float
Decimal
Complex
Bool
String
Tuple
Range
Frozenset
Bytes

Okay, so what’s the point?

Well, it depends on your code and application. Let’s see some Pro’s and Cons of Mutable and Immutable objects

Mutable Objects

Pros

  • Lesser memory management and garbage headache
  • Shorter code if you know what you are doing
  • Faster coding

Cons

  • The code might get really complicated if you don’t know what you are doing
  • Debugging is a bit difficult because change can come from anywhere

Immutable Objects

Pros

  • The object becomes more secure
  • Code becomes predictable as in place changes are resisted
  • Cleaner code in terms of clear return objects from functions and methods

Cons

  • More memory allocation required
  • Memory garbage collection may get stressed

I hope I was able to clear some of the doubts about Mutable and Immutable objects, how to use them and the philosophy behind their existence.

Leave a Reply