Mutable and Imutable Data Types
Mutable and Imutable Data Types
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
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[0] = "pink"
color[-1] = "orange"
print(“List after updating:” , color)
Output:
List before updating : ["red", "blue", "green"]
List after updating : [“pink", “blue", “orange"]