What does immutable mean? Which Python types are mutable and which are not?

ProgrammingPython

In Python, there are two types of Objects.

  • Mutable Object
  • Immutable Object

Mutable: Mutable objects are modified, (i.e) objects are a changeable list, set, dict, etc are mutable.

mutable objects are easy to change.

Example 1

list =["Tutorials ","Point", "Pvt","Ltd"]
list[2]= 'Tutorix'
list

Output

['Tutorials ', 'Point', 'Tutorix', 'Ltd']

Example 2

list=['Car','Bike','Scooty','Bus','Metro']
list[4]= 'Bicycle'
list

Output

['Car', 'Bike', 'Scooty', 'Bus', 'Bicycle']


Immutable: immutable objects are not modified (i.e) not changeable int, float, bool, str, tuple, Unicode, etc ... are immutable. immutable objects are expensive and difficult to change. a tuple is enclosed within the parenthesis tuples are immutable and can't be changed.

Example 1

tuple=('1','2','Python','Perl')
tuple

Output

('1', '2', 'Python', 'Perl')

Example 2

tuple=('1','2','Python','Perl')
tuple[4]='2019'
tuple

Output

TypeError Traceback (most recent call last)
in
1 tuple=('1','2','Python','Perl')
----> 2 tuple[4]='2019'
3 tuple
TypeError: 'tuple' object does not support item assignment


tuple object cant be changed by seeing above output you get a clear understanding

raja
Sri
Published on 28-Jun-2019 19:00:22
Advertisements