96

I run the following in the Python interpreter:

>>> foo = 10
>>> dir(foo) == dir(10)
True
>>> dir(foo) is dir(10)
False
>>> 

Why is this?

ben
  • 1,583
  • 2
  • 11
  • 12

1 Answers1

165

is checks that 2 arguments refer to the same object, == checks that 2 arguments have the same value. dir() returns a list which contains the same data for both foo and 10, but the actual list instances for the 2 things are different.

Silas Ray
  • 25,682
  • 5
  • 48
  • 63
  • 63
    A good example is 1==True returns True, but 1 is True returns False. – Andrew Nov 05 '13 at 21:22
  • 9
    An even more directly relevant point is that `dir(10) is dir(10)` won't even be `True` (barring some sort of interpreter optimization), while `dir(1) == dir(10)` will be `True`. – Silas Ray Oct 26 '15 at 22:58
  • 3
    You can say that "is" in python is the same to "===" in other languages like PHP. – Máxima Alekz Sep 26 '17 at 14:49
  • This probably belongs in a separate question, but are numbers objects in python? How come `1 is 1` returns `True` ? – Nathan majicvr.com Jun 01 '18 at 08:17
  • 4
    @frank Yes, integers are objects. Try `type(1)` or `a = 1;a.__class__` etc. You'd have to get in to pretty deep internals of the parser to understand fully what integers have what identities (there's some interning, and other singleton-driven optimization going on if memory serves), but suffice to say 2 expressions composed of integer literals can sometimes be the same object and sometimes not. For example, at least in my Python 3.6, `1 is 1` and `a = 1;b = 1;a is b` are both `True` but `1 is 10 / 10` is `False`. – Silas Ray Jun 01 '18 at 16:35