Archive - Originally posted on "The Horse's Mouth" - 2016-10-30 11:01:30 - Graham Ellis
"Equality" ... lovely subject. We're all equal in the eyes of many laws these days - man or workman, able bodied or not, young or old, left or right handed, any colour or religion. But just because we're equal doesn't mean we're the same.
In Python, the == operator returns True if the two parameters passed to it have an equal value, whether or not the two objects are the same object. Whereas the is operator only returns True if the parameters and one and the same object (i.e. if the id function returns the same value on both of the). Example program [here].
>>> a = [2,3,4]
>>> b = [2,3,4]
>>> a == b
True
>>> a is b
False
>>> c = a
>>> a == c
True
>>> a is c
True
>>>
Note that many simple immutable objects (such as integers) are only held once on the heap, and you may be surprised to get back a True response from is when you compare two variables derived in different ways. That's not the case for mutable objects such as types you're likely to create for yourself, or for lists and dicts.
You can override the == operator in your own classes by specifying a __eq__ method.