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?
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.
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 .
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 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.
==
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With