Fix Python – Python != operation vs “is not”

Question

Asked By – viksit

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?

Now we will see solution for issue: Python != operation vs “is not”


Answer

== 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.

This question is answered By – Thomas Wouters

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0