Python != operation vs "is not"

viksit picture viksit · Feb 5, 2010 · Viewed 209.5k times · Source

In a comment on this question, I saw a statement that recommended using

result is not None

vs

result != None

I was wondering what the difference is, and why one might be recommended over the other?

Answer

Thomas Wouters picture Thomas Wouters · Feb 5, 2010

== is an equality test. It checks whether the right hand side and the left hand side are equal objects (according to their __eq__ or __cmp__ methods.)

is is an identity test. It checks whether the right hand side and the left hand side are the very same object. No methodcalls are done, objects can't influence the is operation.

You use is (and is not) for singletons, like None, where you don't care about objects that might want to pretend to be None or where you want to protect against objects breaking when being compared against None.