Its been a couple of days since I started learning python, at which point I stumbled across the == and is. Coming from a java background I assumed == does a comparison by object id and is by value, however doing
>>> a = (1,2)
>>> b = (1,2)
>>> a is b
False
>>> a == b
True
Seems like is is equivalent of java’s == and python’s == is equivalent to java’s equals(). Is this the right way to think about the difference between is and ==? Or is there a caveat?
ischecks that both operands are the same object.==calls__eq__()on the left operand, passing the right. Normally this method implements equality comparison, but it is possible to write a class that uses it for other purposes (but it never should).Note that
isand==will give the same results for certain objects (string literals, integers between -1 and 256 inclusive) on some implementations, but that does not mean that the operators should be considered substitutable in those situations.