Operator precedences

Hans Nowak wurmy at earthlink.net
Tue Feb 25 19:48:32 EST 2003


Jesper Hansen wrote:
> In what order are compare operators evaluated?
> 
> According to http://www.python.org/doc/current/ref/summary.html they all
> have the same precedence and are evaluated from right to left, 

No, it says:

"Operators in the same box group left to right (except for comparisons, which 
chain from left to right -- see above, and exponentiation, which groups from 
right to left)."

> but this
> does not seem to true in python 2.2.2.
> 
> These both evaluate to true, so the order does not seem to be fixed;
> (3 < 2 < 1)  ==  (3 < (2 < 1))
> (1 < 2 < 3)  ==  ((1 < 2 ) < 3)

3 < 2 < 1 is equivalent to 3 < 2 and 2 < 1, including the shortcut effect of 
the and operator.

Let's find out if that is true:

 >>> def f(x):
	print x, "!"
	return x

 >>> f(3) < f(2) < f(1)
3 !
2 !
0

Aha, f(1) isn't evaluated at all because f(3) < f(2) is false, so the result of 
the whole expression (f(3) < f(2) and f(2) < f(1)) is already known.

 >>> f(1) < f(2) < f(3)
1 !
2 !
3 !
1

Here, f(1) < f(2) is true, so f(2) < f(3) is evaluated as well.

HTH,

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
Kaa:: http://www.awaretek.com/nowak/kaa.html
Soon: http://zephyrfalcon.org/





More information about the Python-list mailing list