== and is in python
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?
is checks 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 is and == 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.
- '==' checks for equality,
- 'is' checks for identity
To follow up on @CRUSADER's answer:
== checks the equality of the objects, using the eq method.
is checks the actual memory location of the objects. If they are the same memory location, they test as True
As was mentioned above, the first 2**8 integers are stored in memory locations for speed, so to see whats going on use some other object or integers above 256. For instance:
In : a = 1001 In : b = a # this sets a pointer to a for the variable b In : a == b Out: True # of course they are equal In : a is b Out: True # and they point to the same memory location In : id(a) Out: 14125728 In : id(b) Out: 14125728
In : b = 1001 #this instantiates a new object in memory In : a == b Out: True In : a is b Out: False #now the memory locations are different In : id(a) Out: 14125728 In : id(b) Out: 14125824
The difference between is and == confused me originally as well, since they both seem to have the same affect on strings. This similarity disappears for any mutable objects (that are not aliased... which is one of the things is is useful for detecting: aliasing) that you try comparing with is. Copying a mutable object is the easiest way to see this. I'll demonstrate that, as well as the usefulness in detecting aliasing below:
>>> a=[1,2,3] >>> b=a[:] >>> a [1, 2, 3] >>> b [1, 2, 3] >>> a==b True >>> a is b False >>> c=a >>> a==c True >>> a is c True >>>
(taken directly from my IDLE shell) Notice that == essentially compares the value, while is compares the object's identity (the memory location of the object, which can be retrieved with id(some_object)). This can be a bit confusing, but if you understand how data is stored in python, it becomes a bit easier to understand this.