Python Immutable types

Certain types of data like tuples are immutable but what really makes them immutable cause can’t we just change the value of the data by just deleting and replacing it with new values?

A variable can refer to any object, whether immutable or not. If the object is immutable it doesn’t prevent us from pointing the variable to a new object.

>>> string = "some text value"
>>> string[0] = "S"
Traceback (most recent call last):
  File "<pyshell#82>", line 1, in <module>
    string[0] = "S"
TypeError: 'str' object does not support item assignment
>>> string = string[0].upper() + string[1:]
>>> string
'Some text value'
>>> 

We have not mutated the string, only made a new one from the old one.

1 Like