Why are Python strings immutable?
Python strings are immutable which means that once created they can’t be changed. When you try to modify an existing string variable, a new string is created.
Every object in Python is stored in memory. You can find out whether two variables are referring to the same object or not by using the id(). The id() returns the memory address of that object.
Example:
str1="Hello" print("Str1 is: ", str1) print("ID of str1 is:", id(str1)) str2="World" print("Str2 is: ", str2) print("ID of str2 is:", id(str2)) str1+=str2 print("Str1 after concatenation is: ", str1) print("ID of str1 is: ", id(str1)) str3=str1 print("str3= ", str3) print("ID of str3 is:", id(str3))
Output:
Str1 is: Hello
ID of str1 is: 47159616
Str2 is: World
ID of str2 is: 47159840
Str1 after concatenation is: HelloWorld
ID of str1 is: 47226016
str3= HelloWorld
ID of str3 is: 47226016
In this program and its output, it is very clear that str1 and str2 are two different string objects with different values and they have different memory addresses. When we concatenate str1 and str2, a new string is created because Python strings are immutable.