If strings stay in memory in a normal way,How to explain this case?
s1=';;'
s2=';;'
s1==s2,s1 is s2
(True, False)
s1=';'
s2=';'
s1==s2,s1 is s2
(True, True)
If strings stay in memory in a normal way,How to explain this case?
s1=';;'
s2=';;'
s1==s2,s1 is s2
(True, False)
s1=';'
s2=';'
s1==s2,s1 is s2
(True, True)
In the first case, s1
and s2
have equal value, but are not the same instance.
In the second case, s1
and s2
also have equal value, but since they are only single-character strings, and each character is the same as itself, Python interprets this to checking that the characters are the same character, which they are.
Python does this because it uses a cache for small numbers, and single-characters.
You can read more on this question, specifically, this answer.
==
operator checks for equality of value.
is
checks if both entities are pointing to the same memory location.
Now, if the entities are essentially the same object, like s1=s2=";;"
, then s1 is s2
will be True. This is easy to understand.
But we intuitively think that two entities which were initialised separately will have different memory locations. But its not always true.
To improve performance, python just returns back a reference to the existing object, when we create an int(for some range of values), string(again for some range).