The is
command compares object instance references. If the two comparison terms are references of the same object instance then the is
returns true. Your comparison will return true if you use the ==
command, it compares the values.
In short:
- == is used to compare values.
-
is
is for comparing references.
There you compare me: ah, but 'foobar' is 'foobar'
returns true
.
True, but this is because Python caches small values, so this is
comparison can be confusing, please follow:
>>> s1 = 'foo'
>>> s2 = 'foo'
>>> s1 is s2
True
>>> s1 = 'foo!'
>>> s2 = 'foo!'
>>> s1 is s2
False
>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'
True
>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'
False
How far does Python cache a value? What is a large value? A small value?
To delve into the subject I recommend reading this article:
Internals in Python