'is not' or '!='

Marko Rauhamaa marko at pacujo.net
Mon Aug 18 16:53:49 EDT 2014


"ElChino" <elchino at cnn.cn>:

> A newbie question to you; what is the difference between statements
> like:
>  if x is not None:
> and
> if x != None:

Do the following: take two $10 bills. Hold one bill in the left hand,
hold the other bill in the right hand.

Now, the bill in the left hand "is not" the bill in the right hand.
However, the bill in the left hand "==" the bill in the right hand.

> Without any context, which one should be preferred?
> IMHO, the latter is more readable.

In almost all cases, both tests would result in the same behavior.
However, the "is not" test is conceptually the correct one since you
want to know if x is the one and only None object. You don't want to be
fooled by an imposter object that simply looks like the None object.
Frankly, I don't know of any other object that is "==" to the None
object except None itself, but such objects could possible exist.


Marko



More information about the Python-list mailing list