Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Why are Python Strings Immutable?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

An unchanging article alludes to the item which is once made can’t change its worth all its lifetime.  Attempt to execute the accompanying code: 

Python3




name_1 = "Aarun" 
  
name_1[0] = 'T' 

You will get a mistake message when you need to change the substance of the string. 

Traceback (latest call last):  
Record "/home/ca508dc8fa5ad71190ca982b0e3493a8.py", line 2, in <module>  
name_1[0] = 'T'  
TypeError: 'str' object doesn't uphold thing task  

Arrangement  

One potential arrangement is to make another string object with vital alterations: 

Python3




name_1 = "Aarun"
  
name_2 = "T" + name_1[1:]
  
print("name_1 = ", name_1, "and name_2 = ", name_2)

Output:

name_1 =  Aarun and name_2 =  Tarun

To watch that they are various strings, check with the id() work: 

Python3




name_1 = "Aarun"
name_2 = "T" + name_1[1:]
  
print("id of name_1 = ", id(name_1))
print("id of name_2 = ", id(name_2))

Output:

id of name_1 =  2342565667256
id of name_2 =  2342565669888

To see more about the idea of string permanence, think about the accompanying code: 

Python3




name_1 = "Aarun"
name_2 = "Aarun"
  
print("id of name_1 = ", id(name_1))
print("id of name_2 = ", id(name_2))

At the point when the above lines of code are executed, you will find that the id’s of both name_1 and name_2 objects, which allude to the string “Aarun”, are the equivalent.  

To burrow further, execute the accompanying assertions: 

Python3




name_1 = "Aarun"
print("id of name_1 = ", id(name_1))
  
name_1 = "Tarun"
print("id of name_1  with new value = ", id(name_1))

Output:

id of name_1 =  2342565667256
id of name_1  with new value =  2342565668656

As can be found in the above model, when a string reference is reinitialized with another worth, it is making another article instead of overwriting the past worth.  

Note: In Python, strings are made changeless so software engineers can’t adjust the substance of the item. This keeps away from superfluous bugs.


My Personal Notes arrow_drop_up
Last Updated : 26 Dec, 2020
Like Article
Save Article
Similar Reads
Related Tutorials