What are Mutable and Immutable? Why we know about mutable and immutable? There are a bunch of questions that arise in everyone's mind but no one knows the exact mean of this. Usually, this topic arises when in an interview, the interviewer asks "what is the difference between list and tuple?" and students point out this topic.
But what is exactly the meaning of mutable and immutable? what is the difference? Let's find out:
According to the Dictionary, mutable means "liable to change"
Mutable data types are those datatypes whose value can be changeable in the same memory location even after declaring its variable.
For ex: the list is a mutable data type.
Let's declare its variable and check for its memory id:-
>>> s=[1,2,3]
>>> id(s)
178540
Now let's update any item and check for id:-
>>> s[1]=4
>>> print(s)
[1,4,3]
>>> id(s)
178540
If you don't understand the code. Don't worry you will learn about it in a few chapters later. Now you can clearly see that ID did not change.
Let's take another example of an immutable data type(tuple's) variable and try to update it.
>>> s=(1,2,3)
>>> print(s)
(1,4,3)
>>> id(s)
175468
>>> s[1]=4
Traceback (most recent call last):
File "<pyshell#1>", line 1, in
s[1]=4
TypeError: 'tuple' object does not support item assignment
we can clearly see that we can't update any item value. which shows it is an immutable datatype.
Now, let's see which are mutable and immutable data types:
Mutable Datatypes: List, Dictionary, Set
Immutable Datatypes: Int, Float, String, Tuple, Complex, Bool, Numpy object.
you can also ask for this example:
>>> a=10
>>> id(a)
178580
>>> a=a+2
>>> a=12
>>> id(a)
175892
we are able to update here, how can int be immutable. So for that, if you pay attention then you are not updating the value of a, instead, you just re-declaring an again. You can verify this by comparing id before and after the update.
If you think this topic is far more for you to understand, you can skip it now and come back when you completed List and Tuple.
-----------------------------------------------------------------------------------------------------------------------------
Comments
Post a Comment