Reputation: 4770
Can someone explain how these results are possible (python 2.6):
>>> 1<3>2
True
>>> (1<3)>2
False
>>> 1<(3>2)
False
I would think that one of the last two would match the first one, but apparently the operators in the first statement is somehow linked?!
Upvotes: 1
Views: 203
Reputation: 251378
Your first example shows comparison chaining. 1<3>2
means 1<3 and 3>2
(except each expression is evaluated only once). This applies to all comparison operators in Python.
Your second two examples force one comparison to be evaluated first, resulting in a boolean value which is then compared with the remaining integer.
Upvotes: 9
Reputation: 5540
As per docs,
Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics:
comparison ::= or_expr ( comp_operator or_expr )*
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "<>" | "!=" | "is" ["not"] | ["not"] "in"
Comparisons yield boolean values:
True
orFalse
.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).
Upvotes: 1
Reputation: 1122032
The last two statements compare booleans against an integer:
>>> True > 2
False
>>> 1 < True
False
The first statement is comparison chaining, which works for all boolean comparisons in Python. Note from the documentation:
Comparisons yield boolean values: True or False.
By placing parts of your expression in brackets, those parts get evaluated first and you end up with comparing integers and booleans.
Upvotes: 2
Reputation: 10541
In your first case 1<3>2
1
is actually lesser than 3
and 3
is greater than 2
, so True
.
In your second case (1<3)>2
(1<3)
evaluates as True
that represented as 1
, so 1
is not greater than 2
.
In your third case 1<(3>2)
, 1
is not lesser than True
that represented as 1
.
Upvotes: 4