Why does the identity value change every time when the assignment is the same?
Course: Learn Python 3 from Scratch - Free Interactive Course
Lesson: Strings - Learn Python 3 from Scratch
Why does the identity value change every time when the assignment is the same?
Course: Learn Python 3 from Scratch - Free Interactive Course
Lesson: Strings - Learn Python 3 from Scratch
Hi @1158013027 !!
Thanks for contacting the Educative Team. Python strings are immutable, they can’t be modified once they are created. So when we are trying to update the value of variable str1
, a new object will be created with the changed value as we can’t perform any changes in the existing object. That’s why identity value of string object changes every time.
str1 = "hello"
print(id(str1))
str1 = "bye"
print(id(str1))
Output:
I hope it helps. Happy Learning
But I’m able to print the str1 on both lines and once it print hello and for the next line print bye
Yes you are right. The following code:
str1 = "hello"
print(id(str1))
print(str1)
str1 = "bye"
print(id(str1))
print(str1)
will give this output:
Here, we cannot modify the value of str1
after its creation but when we update the value of str1
from hello
to bye
a new object will be created for each assignment.
I hope this helps. Happy Learning