Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inequalities: != vs not ==

I realized today while writing some Python that one could write the inequality operator as a!=b or not a==b. This got me curious:

  1. Do both ways behave exactly the same, or are there some subtle differences?
  2. Is there any reason to use one over the other? Is one more commonly used than the other?
like image 364
Theron Luhn Avatar asked May 03 '12 04:05

Theron Luhn


People also ask

What is == and != In Python?

== Equal to - True if both operands are equal. x == y. != Not equal to - True if operands are not equal.

Can we use != In Python?

Not Equal Operator in Python If the values compared are equal, then a value of true is returned. If the values compared are not equal, then a value of false is returned. != is the symbol we use for the not equal operator.

How do you check for equality inequalities 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. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None .

Is is the same as == in Python?

Put simply: == determines if the values of two objects are equal, while is determines if they are the exact same object.


1 Answers

  1. == invokes __eq__(). != invokes __ne__() if it exists, otherwise is equivalent to not ==.
  2. Not unless the difference in 1 matters.
like image 57
Ignacio Vazquez-Abrams Avatar answered Sep 22 '22 06:09

Ignacio Vazquez-Abrams