Difference between
mutable and immutable in Python
1.
Meaning of mutable is changeable, reverse of
mutable is immutable. It means not changeable.
2.
These mutable and immutable terms are used to
refer Python objects.
3.
Every language has their own definition for
their usage.
In Python following objects are immutable
·
int
·
float
·
decimal
·
complex
·
bool
·
string
·
tuple
·
range
·
frozenset
·
bytes
Following objects are mutable
·
list
·
dict
·
set
·
bytearray
·
user-defined classes (unless specifically made immutable)
Sample:
1. Trying to
change value of the immutable string object
sample_str =
'mutable test?'
sample_str[11]
= '!'
The above written program throws following error since we can’t
modify the immutable objects
>>>
Traceback (most
recent call last):
File
"C://Python_Practice/mutablevsimmutable.py", line 2, in
sample_str[11] = '!'
TypeError: 'str'
object does not support item assignment >>>
2. Trying to modify the mutable
object
int_list_sample = [10, 6,4]
int_tuple_sample
= (10, 6,4)
print("list
before modify :", int_list_sample)
int_list_sample[0]
= 1
#
list is now [10, 6,4]
print("list
after modify :", int_list_sample)
int_tuple_sample[0]
= 1
#
should raise: TypeError: 'tuple' object does not support item assignment
Output
for the above program is
list
before modify : [10, 6, 4]
list
after modify : [1, 6, 4]
Trackback (most recent call last):
File
"C:/Jeyanthi/Python_Practice/mutablelist.py", line 10, in
int_tuple_sample [0] = 1
TypeError: 'tuple' object does not support item assignment
In this
example, list is mutable so it allows the user to the modify the object. Tuple is
immutable so it raises error when the user tries to modify it.
Note: # is commented line in Python
To remember easily we can define that Primitive
data types are immutable. Container data types are mutable in python.