checking if two things do not equal None

Chris Angelico rosuav at gmail.com
Sun Mar 30 02:17:34 EDT 2014


On Sun, Mar 30, 2014 at 4:54 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Sun, 30 Mar 2014 13:15:18 +1100, Chris Angelico wrote:
>
>> Chained comparisons where you're checking a single variable against two
>> constants make perfect sense:
>>
>> 2 < x < 5
>>
>> Chained comparisons where you check a single constant against two
>> variables don't, so much:
>>
>> x < 2 < y
>>
>> What exactly does that mean, and why is it written that way?
>
> It checks that 2 is strictly bounded between x on the left and y on the
> right, i.e. that 2 is inside the open interval x...y. I don't know why
> you think that's unclear. But then I do have a maths background and I'm
> used to chaining comparisons.
>
> Write it like this:
>
> low = x
> high = y
> a = 2
>
> low < a < high
>
> Does that make more sense? Well-chosen names are good. The fact that a is
> a constant rather than a variable is no big deal:
>
> low < 2 < high

The problem isn't that I can't see what the comparisons are. It makes
very good sense to bound a variable within constants; but you already
know exactly where 2 is on the number line, so asking "Is 2 between
these two variables" seems a bit odd. Maybe it's less so with the
strong mathematical background, but it seems odd to me.

>> It'd be more useful but less clear if one of the conditions points the
>> other way:
>>
>> x < 2 > y
>>
>> which checks that they're both less than two,
>
> which is quite different from what you wrote the first time.
>
>
>> but IMO in a less-than-clear way.
>
> That's an understatement. If I saw code chaining comparisons in that
> fashion, I would assume the second operator > was a typo.
>
> Chaining less-than and greater than operators should, for clarity, always
> be written in a single order. E.g. a <= b < c < d, not a <= b < d > c.
>
> (The second contains a subtle bug too.)

Agreed.

ChrisA



More information about the Python-list mailing list