1.

Explain concept of mutable vs immutable object in Python.

Answer»

Each Python object, whether REPRESENTING a built-in class or a user defined class, is stored in computer’s memory at a certain randomly chosen location which is returned by the built-in id() function.

>>> x=10 >>> id(x) 94368638893568

Remember that VARIABLE in Python is just a label bound to the object. Here x represents the integer object 10 which is stored at a certain location.

Further, if we assign x to another variable y, it is also referring to the same integer object.

>>> y=x >>> id(y) 94368638893568

Let us now change value of x with expression x=x+1. As a result a new integer 11 is stored in memory and that is now referred to by x. The object 10 continues to be in memory which is bound to y.

>>> x=x+1 >>> id(x) 94368638893600 >>> id(y) 94368638893568

Most striking feature is that the object 10 is not changed to 11. A new object 11 is created. Any Python object whose value cannot be changed after its creation is IMMUTABLE. All number type objects (int, float, complex, bool, complex) are immutable.

STRING object is also immutable. If we try to modify the string by replacing one of its characters, Python interpreter doesn’t allow this, raising TypeError thus implying that a string object is immutable.

>>> string='Python' >>> string[2]='T' Traceback (most recent call last):  File "<pyshell#9>", line 1, in <module>    string[2]='T' TypeError: 'str' object does not support item assignment

Same thing is true with tuple which is also immutable.

>>> TUP=(10,20,30) >>> tup[1]=100 Traceback (most recent call last):  File "<pyshell#11>", line 1, in <module>    tup[1]=100 TypeError: 'tuple' object does not support item assignment

However, list and dictionary objects are mutable. These objects can be updated in place.

>>> num=[10,20,30] >>> num[1]=100 >>> num [10, 100, 30] >>> dct={'x':10, 'y':20, 'z':30} >>> dct['y']=100 >>> dct {'x': 10, 'y': 100, 'z': 30}


Discussion

No Comment Found