While this question doesn't have any real use in practise, I am curious as to how Python does string interning. I have noticed the following.
>> "string" is "string"
>> True
This is as I expected.
You can also do this.
>> "strin"+"g" is "string"
>> True
And that's pretty clever!
But you can't do this.
>> s1 = "strin"
>> s2 = "string"
>> s1+"g" is s2
>> False
Why wouldn't Python evaluate s1+"g"
, realise it is the same as s1
and point it to the same address? What is actually going on in that last block to have it return False
?
This is implementation-specific, but your interpreter is probably interning compile-time constants but not the results of run-time expressions.
In what follows I use CPython 2.7.3.
In the second example, the expression
"strin"+"g"
is evaluated at compile time, and is replaced with"string"
. This makes the first two examples behave the same.If we examine the bytecodes, we'll see that they are exactly the same:
The third example involves a run-time concatenation, the result of which is not automatically interned:
If you were to manually
intern()
the result of the third expression, you'd get the same object as before:Case 1
Case 2
Now, your question is why the id is same in case 1 and not in case 2.
In case 1, you have assigned a string literal
"123"
tox
andy
.Since string are immutable, it makes sense for the interpreter to store the string literal only once and point all the variables to the same object.
Hence you see the id as identical.
In case 2, you are modifying
x
using concatenation. Bothx
andy
has same values, but not same identity.Both points to different objects in memory. Hence they have different
id
andis
operator returnedFalse