
Introduction
In Python, every variable stores an instance of an object. in python there are two types of objects:
- Mutable
- Immutable
When we instantiate an object in Python, we assign, that object is assigned with some unique ID. At the runtime, that object is defined and can’t be changed after. But if it is a mutable object its state can be changed.
Immutable Objects
These objects are in-built types for example int, bool, float, string, and tuple. simple, these objects can not be changed once created.
Code
Output
In the above code, we tried to change the tuple, and because of it, it gave a Type Error. A tuple is an immutable object, once created can not be altered.
Mutable Objects
Mutable Objects: These are the objects that can be changed after creation. Custom classes generally are mutable. Some mutable types are list, set, dictionary etc.
Code
Output
Conclusion
- In Python, objects are handled differently when it comes to their type. When we talk about immutable objects, they are quick to access but with great cost as they can not be changed because it involves the creation of a copy. On the other hand, mutable objects can be changed easily.
- Whenever a change is required in data, mutable objects should be used.
- Tuple itself is not mutable but its content or elements are mutable.
- Generally, Primitive types are mostly immutable and Customized types are probably mutable.
Code
Output
In the code, we can see that the first element of the tuple is a list that is mutable and is changed. However, the tuple itself is not mutable and cannot be changed.
Some examples explaining the exception of tuple
Code
Output
Explanation
In the code above, we created a tuple named tup in which there is an element that is a list and we know that list is a mutable object, so we changed the list and as we can see the output. The tuple itself is immutable and can not be updated but if there is a mutable object in the tuple then in some way the tuple can be changed but that does not make it mutable.