1

Possible Duplicate:
Python “is” operator behaves unexpectedly with integers

I'm learning Python, and am curious as to why:

x = 500
x is 500

returns False, but:

y = 100
y is 100

returns True?

Community
  • 1
  • 1
Connor
  • 4,138
  • 8
  • 34
  • 51

3 Answers3

8

Python reuses small integers. That is, all 1s (for example) are the same 1 object. The range is -5 to 255, if I remember correctly, though this is a CPython implementation detail that should not be relied upon. I am pretty sure Jython and IronPython, for example, handle this differently.

The reason this works out fine is that ints are immutable. That is, you can't change a 4 to a 5 in-place. if a has a value of 4, a = 5 is actually pointing a to a different object, not changing the value a contains. Python doesn't share any mutable types (such as lists) where unexpectedly having multiple references to the same object might cause problems.

You should use == for comparing most things. is is for checking to see whether two references point to the same object; it is roughly equivalent to id(x) == id(y).

kindall
  • 178,883
  • 35
  • 278
  • 309
  • I think at least some IronPython versions might: 3.0 gave True for the 500 case, and it looks like the first int which isn't intern-optimized is 1000. – DSM Sep 24 '12 at 00:47
4

is tests for identity - x is y asks if they are the same object, not if they are simply 'equivalent'. So you also have, eg:

>>> x = []
>>> y = []
>>> z = x
>>> x is y
False
>>> x is z
True

For equivalence, you want to test equality:

>>> x = 500
>>> x == 500
True

Python (or, at least, cpython - the major implementation) does some optimisations so that certain immutable objects only exist once throughout the lifetime of the interpreter. So, every 5 throughout your program will be the same integer object. The same thing happens with string literals, for example.

lvc
  • 34,233
  • 10
  • 73
  • 98
3

"is" compare objects IDs and "==" will compare object values. So, if you need to compare values, go with "==" and if you whant to compare objects, go with "is".

As in Python everything is an object, is compares objects IDs, it's faster, but some times unpredictable. You need to be very sure of what you are doing to use "is" for simple comparsion.

About the situation above, I found here: http://docs.python.org/c-api/int.html the following remark:

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)

So, you can do the following test and see this behaviour:

>>> a = 256
>>> id(a)
19707932
>>> id(256)
19707932
>>> a = 257
>>> id(a)
26286076
>>> id(257)
26286064

So, for integers above 256, "is" will not work. Be careful using "is" for comparsion.