checking if two things do not equal None

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Mar 29 22:24:59 EDT 2014


On Sat, 29 Mar 2014 17:36:55 -0500, Tim Chase wrote:

> And for cases where you have more than one or two things to test for
> None-itude, you could use
> 
>   if all(x is None for x in [a, b, c, d]):
>     do_something_if_theyre_all_None()
> 
> or
> 
>   if all(x is not None for x in [a, b, c, d]):
>     do_something_if_no_Nones()
> 
> or
> 
>   if not any(x is None for x in [a, b, c, d]):
>     do_something_if_no_Nones()
> 
> which I find *much* more readable from a maintenance point of view.

With one or two things, I would stick to a regular comparison (skipping 
the "not"):

a is None
a is b is None

With three, I would consider either idiom:

a is b is c is None
all(x is None for x in (a, b, c))

but lean towards the use of all(). From four onwards I would definitely 
use all(), and of course if there is an arbitrary number of items, I 
would definitely use all().



-- 
Steven D'Aprano
http://import-that.dreamwidth.org/



More information about the Python-list mailing list