Why does comparing strings using either '==' or 'is' sometimes produce a different result?

jottos picture jottos · Oct 1, 2009 · Viewed 1.6M times · Source

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

SilentGhost picture SilentGhost · Oct 1, 2009

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: a is b is the equivalent of id(a) == id(b)