Work with Mutable and Immutable Objects
The immutable term generally refers to their property of being immune to change or modification after their creation, the same case with the string data type in Python which is immutable.
Some other datatypes in Python are immutable such as strings, numbers (integers, floats, complex numbers), tuples, and frozensets.
Mutable objects are that we can modify according to our requirements and use according to our use. A few examples of them are List, Dictionary, and Set.
Example:
In the below code, we declare a string and assign it to modify the “my_string” variable, after that we try the string.
Python3
my_string = "Hello, world!" # Attempt to modify the string my_string[ 0 ] = 'h' # Raises TypeError: 'str' object does not support item assignment----- |
Output:
Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 4, in <module>
my_string[0] = 'h' # Raises TypeError: 'str' object does not support item assignment-----
TypeError: 'str' object does not support item assignment
Why are Python Strings Immutable?
Strings in Python are “immutable” which means they can not be changed after they are created. Some other immutable data types are integers, float, boolean, etc.
The immutability of Python string is very useful as it helps in hashing, performance optimization, safety, ease of use, etc.
The article will explore the differences between mutable and immutable objects, highlighting the advantages of using immutable objects. It will also compare immutability with mutability, discussing various methods to handle immutability and achieve desired outcomes.
Input: name_1 = "Aarun"
name_1[0] = 'T'
Output: TypeError: 'str' object does not support item assignment
Explanation: We cannot update the string after declaring it means once an immutable the objects instantiated, its value cannot be changed