agtoever
agtoever

Reputation: 1699

Why does `a<b<c` work in Python?

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.

Upvotes: 2

Views: 289

Answers (3)

pat
pat

Reputation: 12749

Compare operators can be chained, according to the language reference

https://docs.python.org/2/reference/expressions.html#not-in

Upvotes: 1

Shawn Mehan
Shawn Mehan

Reputation: 4578

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.

Upvotes: 2

mgilson
mgilson

Reputation: 310227

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, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.

Upvotes: 9

Related Questions