What is the justification for Python's power operator associating to the right?

Posted by Pieter Müller on Programmers See other posts from Programmers or by Pieter Müller
Published on 2012-10-12T09:52:39Z Indexed on 2012/10/12 15:49 UTC
Read the original article Hit count: 362

Filed under:
|
|
|
|

I am writing code to parse mathematical expression strings, and noticed that the order in which chained power operators are evaluated in Python differs from the order in Excel.

From http://docs.python.org/reference/expressions.html:

"Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands): -1*2 results in -1."*

This means that, in Python: 2**2**3 is evaluated as 2**(2**3) = 2**8 = 256

In Excel, it works the other way around: 2^2^3 is evaluated as (2^2)^3 = 4^3 = 64

I now have to choose an implementation for my own parser. The Excel order is easier to implement, as it mirrors the evaluation order of multiplication.

I asked some people around the office what their gut feel was for the evaluation of 2^2^3 and got mixed responses.

Does anybody know of any good reasons or conciderations in favour of the Python implementation? And if you don't have an answer, please comment with the result you get from gut feel - 64 or 256?

© Programmers or respective owner

Related posts about python

Related posts about operators