Theron Luhn
Theron Luhn

Reputation: 4092

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?

Upvotes: 13

Views: 25569

Answers (2)

JustinDanielson
JustinDanielson

Reputation: 3185

Be mindful of your parenthesis.

>>> not "test" == True
True
>>> not "test" and True
False

== takes precedence over not. But not and and have the same precedence, so

Python Operators Precedence

Upvotes: 10

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799540

  1. == invokes __eq__(). != invokes __ne__() if it exists, otherwise is equivalent to not ==.
  2. Not unless the difference in 1 matters.

Upvotes: 21

Related Questions