From my understanding, if a variable of an immutable type is assigned a value equal to another variable of the same immutable type, they should both be referencing the same object. I am using Python 2.7.6, don't know if this is a bug.
This behaves like I how understood:
x = 'ab'
y = 'ab'
id(x) == id(y)
True
However, by altering a character, this does not behave:
x = 'a#'
y = 'a#'
id(x) == id(y)
False
Strangely though, parallel assignment is very different!
x, y = 'a#','a#'
id(x) == id(y)
True
I do not understand this behavior.
It means, if two variables are assigned the same string value, they are really referring to the same string object in memory. This fact can be verified by checking their id() value. Hence, comparison operator == for checking equality returns True if two string operands have same id() value, and False otherwise.
Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.
In python programming we can check whether strings are equal or not using the “==” or by using the “. __eq__” function.
What you're talking about is known as string interning. This is an internal mechanism and there is no guarantee that two distinct strings would be stored in the same place in memory. This is not a bug so don't rely on such behavior. This is in the same general category as undefined behavior in C/C++.
You may be interested in this answer.
While I am able to replicate this behavior in the REPL, the comparison always returns true for me if I put the code in a file and then run it with the interpreter.
By the way there is a way to guarantee that the objects are the same though:
>>> x = intern('a#')
>>> y = intern('a#')
>>> x is y
True
More details on the subject can be found in this blog post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With