views:

1468

answers:

12

My Google-fu has failed me.

In Python, are these:

n = 5
# Test one.
if n == 5:
    print 'Yay!'

# Test two.
if n is 5:
    print 'Yay!'

two tests for equality equivalent (ha!)? Does this hold true for objects where you would be comparing instances (a list say)?

Okay, so this kind of answers my question:

l = list()
l.append(1)
if l == [1]:
    print 'Yay!'
# Holds true, but...

if l is [1]:
    print 'Yay!'
# Doesn't.

So == tests value where is tests to see if they are the same object?

+7  A: 

== determines if the values are equivalent, while "is" determines if they are the exact same object.

stephenbayer
+4  A: 

http://docs.python.org/lib/comparisons.html

is tests for identity == tests for equality

Each (small) integer value is mapped to a single value, so every 3 is identical and equal. This is an implementation detail, not part of the language spec though

mmaibaum
+53  A: 

is will return True if two variables point to the same object, == if the objects referred to by the variables are equal.

>>> a = [1, 2, 3]
>>> b = a
>>> b is a 
True
>>> b == a
True
>>> b = a[:]
>>> b is a
False
>>> b == a
True

In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work:

>>> 1000 is 10**3
False
>>> 1000 == 10**3
True

The same holds true for string literals:

>>> "a" is "a"
True
>>> "aa" is "a" * 2
True
>>> x = "a"
>>> "aa" is x * 2
False
>>> "aa" is intern(x*2)
True

Please see this question as well.

Torsten Marek
I like the "1000" example. Its very clear.
Tom
+4  A: 

Your answer is correct. The is operator compares the identity of two objects. The == operator compares the values of two objects.

An object's identity never changes once it has been created; you may think of it as the object's address in memory.

You can control comparison behaviour of object values by defining a __cmp__ method or a rich comparison method like __eq__.

Dave Webb
+2  A: 

http://drj11.wordpress.com/2007/06/11/python-perils-of-«x-is-1»/

+3  A: 

They are completely different. is checks for object identity, while == checks for equality (a notion that depends on the two operands' types).

It is only a lucky coincidence that "is" seems to work correctly with small integers (e.g. 5 == 4+1). That is because CPython optimizes the storage of integers in the range (-5 to 256) by making them singletons: http://www.python.org/doc/2.5/api/intObjects.html#l2h-381

Dan
+5  A: 

Note that this is why if foo is None: is the preferred null comparison for python. All null objects are really pointers to the same value, which python sets aside to mean "None"

if x is True: and if x is False: also work in a similar manner. False and True are two special objects, all true boolean values are True and all false boolean values are False

Ryan
+2  A: 

have a look at http://stackoverflow.com/questions/306313/python-is-operator-behaves-unexpectedly-with-integers

what it mostly boils down to is that "is" checks to see if they are the same object, not just equal to each other (the numbers <256 are a special case)

cobbal
+4  A: 

I believe this similar question might answer your question; http://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python

PatrickJ
+16  A: 

There is a simple rule of thumb to tell you when to use == or is.

  • == is for value equality. Use it when you would like to know if two objects have the same value.
  • is is for reference equality. Use it when you would like to know if two references refer to the same object.

In general, when you are comparing something to a simple type, you are usually checking for value equality, so you should use ==. For example, the intention of your example is probably to check whether x has a value equal to 2 (==), not whether x is literally referring to the same object as 2.


Something else to note: because of the way the CPython reference implementation works, you'll get unexpected and inconsistent results if you mistakenly use is to compare for reference equality on integers:

>>> a = 500
>>> b = 500
>>> a == b
True
>>> a is b
False

That's pretty much what we expected: a and b have the same value, but are distinct entities. But what about this?

>>> c = 200
>>> d = 200
>>> c == d
True
>>> c is d
True

This is inconsistent with the earlier result. What's going on here? It turns out the reference implementation of Python caches integer objects in the range -5..256 as singleton instances for performance reasons. Here's an example demonstrating this:

>>> for i in range(250, 260): a = i; print "%i: %s" % (i, a is int(str(i)));
... 
250: True
251: True
252: True
253: True
254: True
255: True
256: True
257: False
258: False
259: False

This is another obvious reason not to use is: the behavior is left up to implementations when you're erroneously using it for value equality.

John Feminella
+1  A: 

As John Feminella said, most of the time you will use == and != because your objective is to compare values. I'd just like to categorise what you would do the rest of the time:

There is one and only one instance of NoneType i.e. None is a singleton. Consequently foo == None and foo is None mean the same. However the is test is faster and the Pythonic convention is to use foo is None.

If you are doing some introspection or mucking about with garbage collection or checking whether your custom-built string interning gadget is working or suchlike, then you probably have a use-case for foo is bar.

True and False are also (now) singletons, but there is no use-case for foo == True and no use case for foo is True.

John Machin
A: 

@Ryan, @John Machin: "foo is None , foo is True, foo is False" maybe faster and even popular idioms, but I would never rely on such a hidden implementation detail such as singletons/value caching. This is a useful optimization though, but binding your code to it can be a pain when using a language implementation that does not have the same implementation detail, and that could be reasonably possible. Torsten and John Fermilla pointed to this detail as a CPython detail indeed.

@John Machin: "Consequently foo == None and foo is None mean the same." : I would have said "they mean different but they behave the same". As you know a computer is very "pedantic" so I would say precise wording can be a proper attribute of a programmer. Please take this has an hint, as I would, and not "personally".

Dario Cangialosi
`None` is a singleton by definition (http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy); it's NOT a "hidden implementation detail". `if foo == True:` and `if foo is True:` may be popular idioms among the unthinking, but they are always redirected to `if foo:` if they appear in public. Torsten and John Fermilla referred to caching small integer values, which is nothing to do with what what my answer was about.
John Machin
Re "pedantic" and "precise wording": "this has an hint" -> SyntaxError.
John Machin