Python - String Immutability


Advertisements

In python, the string data types are immutable. Which means a string value cannot be updated. We can verify this by trying to update a part of the string which will led us to an error.

# Can not 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 position of the letters of 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 above a and a point to same location. Also N and N also point to the same location.

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

Useful Video Courses


Video

Python Online Training

Most Popular

187 Lectures 17.5 hours

Malhar Lathkar

Video

Python Essentials Online Training

55 Lectures 8 hours

Arnab Chakraborty

Video

Learn Python Programming in 100 Easy Steps

136 Lectures 11 hours

In28Minutes Official

Video

Python with Data Science

75 Lectures 13 hours

Eduonix Learning Solutions

Video

Python 3 from scratch to become a developer in demand

70 Lectures 8.5 hours

Lets Kode It

Video

Python Data Science basics with Numpy, Pandas and Matplotlib

63 Lectures 6 hours

Abhilash Nelson

Advertisements