Python difference between mutable and immutable objects

Some of the differences between the mutable object and immutable object are discussed here. If you do not know what mutable or immutable mean go to the link provided below.

Link :Python mutable objects and immutable objects

i)Changeable or unchangeable nature

The first and obvious difference between the mutable and immutable object is, a mutable object can be changed while the immutable object cannot be changed.

In a mutable object the id (or address) remains the same even after their value is changed. So list, set or dictionary type objects have fix address even if their items are changed.

>>> dic={2:'Two' , 3:'Three' , 8:"Eight"}
>>> id(dic) #address before changing any of the value
>>> dic[3]='Thirty three'
>>> dic
{2: 'Two', 3: 'Thirty three', 8: 'Eight'}
>>> id(dic) #address after changing the dic[3] value

Before changing the dic[3] value the id is 2575312, after changing the value the address is still 2575312.

Immutable objects are not changeable. The tuple objects will have fix item throughout its lifetime. Other immutable types such as string, integer, floating point, byte, frozenset etc. change their id when the value is changed.

>>> ff=90.234 #floating point type
>>> id(ff)
>>> ff=90.1233
>>> id(ff)
>>> B=b'Byte type' #byte type object
>>> id(B)
>>> B=B.replace( b'e' , b'E' )
>>> id(B)
>>> B
b'BytE typE'

ii)Only immutable objects are hashable

Object which has a hash meaning, a constant value throughout its lifetime is known as hashable object. Immutable objects contain hash or unchangeable value throughout its lifetime. The mutable objects on the other hand, are not hashable.

You can obtain the hash of an object using the hash() function. Consider the program below which check the hask of the immutable objects.

>>> tp=(23 ,89, 90)
>>> hash( tp )
>>> fst=frozenset( [23, 89, 891, 901] )
>>> fst
frozenset({89, 891, 901, 23})
>>> hash( fst )

For mutable objects let’s check the hash value.

ls=[23 , 90, 'SSS']
>>> hash(ls)

Run the code above, you will get ‘TypeError: unhashable type: ‘list’‘.

iii)Concatenating immutable objects generate large overhead

Immutable objects like string, byte and tuple when concatenated always produce large overhead. This is due to generation of new objects.

Immutable objects are not changeable, so to generate the new concatenated object it will have to create new object from scratch. Performing concatenation repeatedly will cost overhead equal to the quadratic runtime.

>>> tp=(90 , 89 , 9999)
>>> tp1=(23 , 1000)
>>> tp=tp+tp1 #New object created here
>>> tp
(90, 89, 9999, 23, 1000)

If you want to perform concatenation in tuple you can use list instead.

>>> ls=[90 , 89 , 9999]
>>> ls.extend([23 , 1000])
>>> ls
[45, 90, 911, 23, 1000]

Leave a Reply

Your email address will not be published. Required fields are marked *