educative.io

Str immutability

In String immutability module, it is mentioned Notice, when we assign a new value to str1 (at line 4 ) its identity changes not the value.

str1 = “hello”

print(id(str1))

str1 = “bye”

print(id(str1))

My question is - why does it say str1 VALUE does not change, after line 4 assignment I do see new value “bye” assigned to str1 var?
Or does it mean that a new str1 var gets created in memory with value “bye” and there is still a reference to var str1 with value “hello”?


Course: Educative: Interactive Courses for Software Developers
Lesson: Educative: Interactive Courses for Software Developers

Hello @Rutuja_Bhalchandra
Thanks for reaching out to us. The string data types in Python are immutable. This implies that a string value cannot be changed. Since the string is immutable, we can change the reference to the object but not the object itself.

Hope it will help.
Happy Learning :blush:

Is it mean, every time we assign new reference to a string old reference still present in memory?


Course: Educative: Interactive Courses for Software Developers
Lesson: Educative: Interactive Courses for Software Developers

1 Like