Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python != operation vs "is not"

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?

like image 619
viksit Avatar asked Feb 05 '10 19:02

viksit


People also ask

What does the != operator do in Python?

Not Equal Operator in Python The not equal operator is a relational or comparison operator that compares two or more values (operands). It returns either true or false depending on the result of the operation. If the values compared are equal, then a value of true is returned.

Is != The same as ==?

Equality operators: == and != The result type for these operators is bool . The equal-to operator ( == ) returns true if both operands have the same value; otherwise, it returns false . The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .

What is the opposite of != In Python?

You can use the not equal Python operator for formatted strings (f-strings), introduced in Python 3.6. To return an opposite boolean value, use the equal operator ==. Keep in mind that some fonts change != to look like ≠ !

Is and is not an operator?

is and is not are the identity operators in Python. They are used to check if two values (or variables) are located on the same part of the memory. Two variables that are equal does not imply that they are identical.


1 Answers

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

like image 104
Thomas Wouters Avatar answered Sep 21 '22 02:09

Thomas Wouters