Skip to content
Related Articles

Related Articles

Improve Article

Why are Python Strings Immutable?

  • Last Updated : 26 Dec, 2020
Geek Week

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :