conventions/requirements for 'is' vs '==', 'not vs '!=', etc

John Salerno johnjsal at NOSPAMgmail.com
Mon May 19 23:42:14 EDT 2008


On Mon, 19 May 2008 20:34:22 -0700 (PDT)
notnorwegian at yahoo.se wrote:

> i am confused.
> 
> x=5
> y=5
> 
> x==y -> True
> x is y -> True
> 
> shouldnt x is y return False since they shouldnt(dont?) point to the
> same place in memory, they just store an equal value?
> 

For some immutable values (such as numbers and strings), Python will have separate variables reference the same object, as an optimization. This doesn't affect anything, since the numbers are immutable anyway and a shared reference won't create any unexpected changes.

It also works with small, but not large, strings:

>>> x = 'hello'
>>> y = 'hello'
>>> x == y
True
>>> x is y
True
>>> a = 'this is longer'
>>> b = 'this is longer'
>>> a == b
True
>>> a is b
False
>>> 

In the above example, Python has created only one string called 'hello' and both x and y reference it. However, 'this is longer' is two completely different objects.



More information about the Python-list mailing list