The title says it all. For example 1<2<3 returns True and 2<3<1 returns False.
It's great that it works, but I can't explain why it works... I can't find anything about it in the documentation. It's always: expression boolean_operator expression, not two boolean operators). Also: a<b returns a boolean, and boolean boolean_operator expression does not explain the behaviour.
I'm sure the explanation is (almost) obvious, but I seem to miss it.
This is known as operator chaining. Documentation is available at:
https://docs.python.org/2/reference/expressions.html#not-in
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).
And, if you really like formal definitions:
Formally, if
a,b,c, ...,y,zare expressions andop1,op2, ...,opNare comparison operators, thena op1 b op2 c ... y opN zis equivalent toa op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.
Your multiple operators all have the same precedence, so now it is going to work through them serially. 1<2<3 goes to 1<2 which is T, then 2<3 is T. 2<3<1 has two parts, 2<3 is T, but 3<1 is F so the entire expression evaluates to F.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With