Mutable vs Immutable data types
Mutable vs Immutable Objects in Python
Every variable in python holds an instance of an object.
There are two types of objects in python
i.e. Mutable and Immutable objects.
Immutable Objects :
An immutable object can’t be changed after it is created.
These are of in-built types like int, float, bool, string, tuple.
Mutable Objects :
A mutable object can be changed after it is created.
These are of type List, dictionary, Set .
# Python code to test that tuples are immutable
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
Output:
Error:
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[0]=4
TypeError: 'tuple' object does not support item assignment
# Python code to test that strings are immutable
message = "Welcome to python classes"
message[0] = 'p'
print(message)
Output:
Error :
Traceback (most recent call last):
File "/home/ff856d3c5411909530c4d328eeca165b.py", line 3, in
message[0] = 'p'
TypeError: 'str' object does not support item assignment
# Python code to test that Lists are mutable
color = ["red", "blue", "green"]
print(“List before updating :” , color)
color[0] = "pink"
color[-1] = "orange"
print(“List after updating:” , color)
Output:
List before updating : ["red", "blue", "green"]
List after updating : [“pink", “blue", “orange"]