What is mutable and immutable in Python
In python, every variable holds the instance of an object. There are two types of objects in python, Mutable and Immutable objects. When an object is instantiated, it is assigned a unique object id. The type of this object is defined at the runtime and it can’t be changed afterward. However, it’s state can be changed if it is a mutable object.
Mutable objects can change their state or contents and immutable objects can’t change their state or content.
- Immutable Objects: In-built types like int, float, bool, string, Unicode, tuple. An immutable object can’t be changed after it is created.
t = (1, 2, 3, 4) t = 5 print(t)
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment
- Mutable Objects : list, dict, set are the mutable objects in Python . Custom classes are generally mutable.
week = ["monday", "wednesday", "thursday"] print(week) week="tuesday" print(week)
wednesday ['monday', 'tuesday', 'thursday']
Mutable and immutable objects are handled differently in python. Immutable objects are quicker to access and are expensive to change because it involves the creation of a copy.
Whereas mutable objects are easy to change.
Use of mutable objects is recommended when there is a need to change the size or content of the object.