Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "is None" and "== None"

Tags:

python

I recently came across this syntax, I am unaware of the difference.

I would appreciate it if someone could tell me the difference.

like image 298
myusuf3 Avatar asked Jul 15 '10 16:07

myusuf3


People also ask

Should I use is None or == None Python?

Introduction to the Python None valueIt's a good practice to use the is or is not operator to compare a value with None . Note that you cannot override the is operator behavior like you do with the equality operator ( == ).

Is None vs equal None?

If you want to check whether an object compares equal to None , by all means use obj == None . If you want to check whether an object is None , use obj is None .

What is the difference between IS and == in Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory.

How do you compare None?

Use the is operator to compare to None in Python, e.g. if my_var is None: . The is operator returns True if the two values point to the same object (it checks for identity), whereas the double equals == operator checks if the two values are equal.


1 Answers

The answer is explained here.

To quote:

A class is free to implement comparison any way it chooses, and it can choose to make comparison against None mean something (which actually makes sense; if someone told you to implement the None object from scratch, how else would you get it to compare True against itself?).

Practically-speaking, there is not much difference since custom comparison operators are rare. But you should use is None as a general rule.

like image 76
Ben Hoffstein Avatar answered Oct 15 '22 06:10

Ben Hoffstein