Python - String Immutability

Deepen Sathe

10 months ago

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 lead us to an error.
String Immutability in Python | Insideaiml
String Immutability in Python | Insideaiml

Why is Python Strings Immutable?

One is performance: knowing that a string is immutable makes it easy to lay it out at construction time — fixed and unchanging storage requirements. This is also one of the reasons for the distinction between tuples and lists. This also allows the implementation to safely reuse string objects. For example, the CPython implementation uses pre-allocated objects for single-character strings and usually returns the original string for string operations that doesn’t change the content.
The other is that strings in Python are considered as elemental as numbers. No amount of activity will change the value 8 to anything else, and in Python, no amount of activity will change the string “eight” to anything else.

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

b = 91909376
a = 91836864
n = 91259888
a = 91836864
n = 91259888
Immutability on tuples is only partly true. The tuple itself cannot be modified, but objects referenced by the tuple can be modified. If the tuple has an immutable field like a string, then the tuple cannot be modified and it is sometimes called “non-transitive immutability.” But a mutable field like a list can be edited, even if it’s embedded in the “immutable” tuple.
To learn more about python, visit the InsideAIML page

Submit Review