Loading, please wait...


What are immutable and mutable types in Python?

In this article, we will discuss immutable types, the disadvantages of immutable types, the need for mutable types, and the working of both types.

As you know Python language supports Object-Oriented Paradigm and everything in python behaves like an object, every variable holds an instance of an object. These variables are defined at runtime. Every object in Python has one of the two states, either immutable or mutable.  

Immutable objects are the ones that cannot be changed after creation that means when objects of these classes are used to store values, those values cannot be altered further. They are good variable and value set. These are easy to design and implement. Objects of built-in types like integer, string, etc are immutable.

How Immutable data types work in the memory:

Suppose you are working with a variable ‘a’ and the expression is:

a = 4

In memory, a block will be assigned to this expression. The name of the block will be ‘a’ and the value of the block will be ‘1'. The value can only be accessed using the name. And then you change the value of a. So,

 a = 10

Here when we change the value ‘a’, we are not overwriting ‘a=4’ instead ‘a’ is now pointing at 10. The value ‘4’ is still available in the memory but cannot be accessed as that memory cell has no name now. In other words, when you create a variable and assign it a value, you just simply store the value in the memory block and that variable point towards that value and/or memory block.

So here you can see when we change the value of an immutable type, the value is not actually changed instead the variable starts pointing towards the new value.

The main disadvantage of using an immutable type is that they require a separate object for each distinct value. Whenever we do alteration in values of immutable type, a new memory block is allocated to the new value instead of overwriting the old one. This creates overhead on memory and decreases the efficiency of the program. Because of this property of immutable types, garbage collection is required much more frequently.

So in order to remove this overhead on memory and to improve the efficiency of the program, mutable types are used.

Mutable types can be changed or altered after creation. Objects of built-in types like dict, list, set are mutable types. Custom classes are also mutable types. Mutable types are used where there is a possibility of frequent changes.

Hereafter creating the list we will add/append a new element using append() function.

Now we will delete an element using pop() function.

Now you can see when we used the append() function, a new element has been added to the list and we removed an existing element using pop() function. Hence, mutable types are easy to alter and save memory which increases the efficiency and decreases the overhead.

To know more about various data types supported by python: Click here


Related Article