I've got a Python program where two variables are set to the value 'public'
. In a conditional expression I have the comparison var1 is var2
which fails, but if I change it to var1 == var2
it returns True
.
Now if I open my Python interpreter and do the same "is" comparison, it succeeds.
>>> s1 = 'public'
>>> s2 = 'public'
>>> s2 is s1
True
What am I missing here?
Answer
is
is identity testing, ==
is equality testing. what happens in your code would be emulated in the interpreter like this:
>>> a = 'pub'
>>> b = ''.join(['p', 'u', 'b'])
>>> a == b
True
>>> a is b
False
so, no wonder they're not the same, right?
In other words: is
is the id(a) == id(b)
No comments:
Post a Comment