3 ms·
"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
by 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...]