Python – String Immutability
Python – String Immutability
In python, string data type is immutable. This means that string values cannot be updated. We can verify this by trying to update a part of the string, which will result in an error.
# cannot reassign
t = "Tutorialspoint"
print type(t)
t[0] = "M"
When we run the above program, we get the following output –
t[0] = "M"
TypeError: 'str' object does not support item assignment
We can further verify this by checking the memory location address of the string letter position.
x = 'banana'
for idx in range(0,5):
print x[idx],"=",id(x[idx])
When we run the above program, we get the following output. As you can see, a and a point to the same location. N and N also point to the same location.
b = 91909376
a = 91836864
n = 91259888
a = 91836864
n = 91259888