Python has a varied set of data structures that it comes with. However, all of them get classified into two –
- Mutable Data Types
- Immutable Data Types
In this blog, we will be understanding what is the difference between mutable and immutable data types. But, before we delve deeper into the meaning of both, it is important for us to understand that the when a variable is created, an address block is assigned to that variable. So, the identity of the variable is the address block of which it is part of!
Mutable Data Types – In these data types, you can change the value of the variable, without changing their identity.
Immutable data types – You cannot change the value of this kind of data type without changing its identity.
Let us now understand this with examples –
temp_string = “Avantik”
print(temp_string)
temp_string[0]=”b”
print (temp_string)
The above is a sample code that I tried. Now, in this case, I am trying to change the identity of an object. Well, since this is immutable – string , we are being thrown an error –
temp_string = “Avantik”
print(temp_string)
temp_string[0]=”b”
print (temp_string)
Now, let us look at how the mutable objects will behave –
temp_list = [2,5,6,3]
print(temp_list)
temp_list[0]=”b”
print (temp_list)
In this case, the changes do happen. Because it is mutable. The value for these can be changed. Not that strings are in itself immutable, but they can be stored inside of a mutable object.
Plus Note – The reason for having mutable and immutable objects is because of security. So, the immutable objects do not allow concurrency. These concepts are viable when you understand the concepts of database and operating systems. So, when we say that concurrency is not allowed, it is useful when there are systems with multi users.
Happy Learning 🙂
Leave a comment