HiveBrain v1.2.0
Get Started
← Back to all entries
gotchapythonCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
whyproducestringsdifferentusingdoeseithercomparingresultsometimes

Problem

Two string variables are set to the same value. s1 == s2 always returns True, but s1 is s2 sometimes returns False.

If I open my Python interpreter and do the same is comparison, it succeeds:

>>> s1 = 'text'
>>> s2 = 'text'
>>> s1 is s2
True


Why is this?

Solution

is is identity testing, and == 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)

Code Snippets

>>> a = 'pub'
>>> b = ''.join(['p', 'u', 'b'])
>>> a == b
True
>>> a is b
False

Context

Stack Overflow Q#1504717, score: 1695

Revisions (0)

No revisions yet.