Mutable Vs Immutable types in python

Python represents all its data as objects.Some of the objects like lists and dictionaries are mutable, meaning you can change their content without changing their identity.Other objects like integers, floats,strings, tuples etc are the objects which cannot be changed.

 

Below is an example showing strings are immutable objects

>>> s="abc"
>>> id(s)
3077106312L
>>> s[0]
'a'
>>> s[1]
'b'
>>> s[0]="P"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> s="qwe"
>>> id(s)
3076980912L
>>> s +="jkl"
>>> id(s)
3076970560L
>>>

 

Below is an example showing lists are mutable objects

>>> d=[1, 5, 6]
>>> id(d)
3076965996L
>>> d[0]
1
>>> d[0]=3
>>> d[0]
3
>>> id(d)
3076965996L

Leave a comment