checking if two things do not equal None
steve+comp.lang.python at pearwood.info
Sun Mar 30 08:08:37 CEST 2014
On Sat, 29 Mar 2014 19:54:09 -0700, Rustom Mody wrote:
> On Sunday, March 30, 2014 8:09:45 AM UTC+5:30, Roy Smith wrote:
>> I have no particular problem with
>> x < 2 < y
>> because it fits the same pattern. But, if you show me
>> a != None != b:
>> my brain just goes into overload. Honestly, I don't even know what
>> that means. My brain keeps trying to stick a, None, and b on Mrs.
>> Albaum's number line and keeps walking into the wall. If you (the
>> editorial you) tell me that my failure to grok that expression means
>> I'm not fluent in Python, well then, guilty as charged.
> <Math Terminology>
> So for != chained comparisons are not natural (or IMHO appropriate)
I tend to agree they're "not natural", although appropriate is another
thing. The problem is that we tend to read something like:
a != b != c
as "all of a, b and c are unequal", corresponding to:
a == b == c
as "all of a, b and c are equal". But that's not what it means. It means
that a != b and b != c, but it says nothing about a and c. And that was
my mistake. The OP actually got it right in their first post, but
sticking None in the middle to ensure it partakes of both comparisons.
a is not None is not b
Still, that's not easily extended to a third item, this would be wrong:
a is not None is not b is not c
since c only gets compared against b, not None. Better is to factor the
not (a is b is c is None)
which now should be clear: you're testing whether or not *all* of a, b
and c are None. If you prefer:
not all(x is None for x in (a, b, c))
Which is more readable is a matter of personal preference.
I think Johannes got it right: boolean logic is easier to reason about
when there is a minimum of "not"s.
More information about the Python-list