Immutability of Python strings

Immutability of Python Strings

In Python, string data types are immutable. This means that the value of a string cannot be updated. We can verify this by trying to update a portion of the string, which will result in an error.

# Can not reassign 
t= "Tutorialspoint"
print type(t)
t[0] = "M"

After running 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 address of the letter position in the string.

.
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. Similarly, N and N also point to the same location.

b = 91909376
a = 91836864
n = 91259888
a = 91836864
n = 91259888

Leave a Reply

Your email address will not be published. Required fields are marked *