Python – Why does comparing strings using either ‘==’ or ‘is’ sometimes produce a different result


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

What am I missing here?

Best Solution

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
>>> a is b

so, no wonder they're not the same, right?

In other words: a is b is the equivalent of id(a) == id(b)

Related Question