View By

Categories

 

Mutable vs Immutable Objects in Python example

Updated: Aug 26, 2019


Everything in Python is an object and all objects in Python can be either mutable or immutable.


Immutable objects: An object with a fixed value. Immutable objects include numbers, bool, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored. They play an important role in places where a constant hash value is needed, for example as a key in a dictionary.


Consider an integer → 1 assigned to variable “a”,

>>> a=1
>>> b=
>>> id(a)
4547990592 
>>> id(b)
4547990592 
>>> id(1)
4547990592

Notice id() for all of them them is same. id() basically returns an integer which corresponds to the object’s memory location.


b → a → 1 → 4547990592


Now, let’s increment the value of “a” by 1 so that we have new integer object → 2.

>>> a=a+1
>>> id(a)
4547990624 
>>> id(b)
4547990592 
>>> id(2)
4547990624

Notice how id() of variable “a” changed, “b” and “1” are still same.


b → 1 → 4547990592

a → 2 → 4547990624


The location to which “a” was pointing has changed ( from 4547990592 → 4547990624). Object “1” was never modified. Immutable objects doesn’t allow modification after creation. If you create n different integer values, each will have a different constant hash value.


Mutable objects can change their value but keep their id() like list, dictionary, set.

>>> x=[1,2,3]
>>> y=
>>> id(x)
4583258952 
>>> id(y)
4583258952

y → x → [1,2,3] → 4583258952


Now, lets change the list

>>> x.pop()
>>> x[1,2] 
>>> id(x)
4583258952 
>>> id(y)
4583258952

y → x → [1,2] → 4583258952


x and y are still pointing to the same memory location even after actual list is changed.


42 views1 comment

Help others, write your first blog today! 

Home   |   Contact Us

©2020 by Data Nebulae