3 ms·
As a Python beginner I'm completely flabbergasted... How can this be? And why can't I use "is" to compare integers? This is insane. The quoted stackoverflow is
by teekert 9y ago
As a Python beginner I'm completely flabbergasted... How can this be? And why can't I use "is" to compare integers? This is insane. The quoted stackoverflow is not very readable to me...
By the way y == 257 does work.
- kbp 9y ago"is" is for asking whether two objects are the same exact object in memory. "==" is for asking whether two objects are logically equal, ie, that they represent the same value. As an example: >>> x = [1,2,3] >>> y = [1,2,3] >>> x == y True # two lists with the same values; equal >>> x is y False # two different lists; doesn't matter that they contain the same values >>> z = x >>> z is x True # same list object in memory Because here you want to know if the two integers are logically equal, not if they're necessarily the same object in memory, you want "==" and not "is". Due to an optimisation, "is" might work for small integers, depending on implementation, but the takeaway is not to use "is" for value comparisons; that's what "==" is for.
- mattbreeden 9y agoTo expand on this, python creates some values as singletons to save memory/speed things up because they are used so often. The most well known examples are True/False/None. That's why you can always do None is None, because all None are the same None in memory. Python takes this a step further by creating lower integer singletons. So any integer from 0-256 (not sure about negatives) will always be the same number in memory. Above 256 python will start actually allocating memory for integers, so two of the same number won't be at the same memory address, and there for won't be comparable by 'is'.
- bakery2k 9y ago0-256 not sure about negatives -5 to 256 (inclusive) [https://github.com/python/cpython/blob/master/Objects/longobject.c#L18 https://github.com/python/cpython/blob/master/Objects/longob...]
- tetha 9y agoFor performance reasons, python re-uses the same objects for small integers, which are 0 to 256 if I recall right. This is done so the interpreter doesn't have to allocate a new object whenever your code uses the rare constant "1". Object allocation is slow, after all. Given this, the expression "1" on the current version of cpython returns the same object from the small integer cache every time. Not just an equal object, the very same object. Overall, don't depend on it - it's an optimization and can change all the time.
- bakery2k 9y ago0 to 256 if I recall right -5 to 256 (inclusive) [https://github.com/python/cpython/blob/master/Objects/longobject.c#L18 https://github.com/python/cpython/blob/master/Objects/longob...]