Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple comparison operators in single statement (chaining comparison operators)

Tags:

python

Does this do what I think it does?

assert 1 < 2 < 3

I couldn't find any reference to this in the docs but I saw it in a high rep answer.

It seems to work but it could be luck, like the leftmost resolves to True, then True is used in the other.

I did a few tests and it always work as expected, but I'd like to find a source (a doc) stating explicitly that it is intended.

>>> 1<2<3<4<5
True
>>> 1<2<7<4<5
False
>>> 1<2<3>2<5
True

This rules out the "leftmost first" hypothesis:

>>> 1<3<2
False
>>> (1<3)<2
True
like image 428
Jérôme Avatar asked Apr 28 '17 10:04

Jérôme


People also ask

What are the 5 comparison operators?

Comparison operators — operators that compare values and return true or false . The operators include: > , < , >= , <= , === , and !== .

What are the 6 comparison operators?

A comparison operator compares two values and returns a boolean value, either True or False . Python has six comparison operators: less than ( < ), less than or equal to ( <= ), greater than ( > ), greater than or equal to ( >= ), equal to ( == ), and not equal to ( != ).

How many types of comparison operators are there?

There are six main comparison operators: equal to, not equal to, greater than, greater than or equal to, less than, and less than or equal to.


1 Answers

This is documented in detail in the Expressions chapter of the documentation:

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).

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.

Note that a op1 b op2 c doesn’t imply any kind of comparison between a and c, so that, e.g., x < y > z is perfectly legal (though perhaps not pretty).

like image 61
Eugene Yarmash Avatar answered Sep 18 '22 12:09

Eugene Yarmash