Why is exponential right-evaluated?


a few tests in Python:

2 ** 3
2 ** 3 ** 4
7 - 2 - 3
(2 ** 3) ** 4
2 ** (3 ** 4)

why 2 ** 3 ** 4 is evaluated as 2 ** (3 ** 4) and not (2 ** 3) ** 4 ?

at the opposite almost all operators are evaluated from left to right, example:
7 - 2 - 3 = (7 - 2) - 3 , not 7 - (2 - 3)

the same with + but as it is associative and commutative, that does not matter.

For exponential i tried to understand if it is related to any mathematical property of exponential but i still do not know.

I suppose C/C++ and many other language do the same as Python but still do not know why.


That’s what you expect from {x^y}^z, right?

it is a convention.

What trouble me is that the meaning of associativity in computer science is different than in mathematics:

" The concept of notational associativity described here is related to, but different from, the mathematical associativity."

different than: Associative property - Wikipedia

see: Serial exponentiation

Why do you say that? Exponentiation is not an associative operation in mathematics.


A left to right 1 dimensional way of writing down x^{y^z} writes x <some operator> y <some operator> z. In math, the convention is that x^{y^z} means y^{(y^z)}, not \left(x^y\right)^z. Latex (which I am using here) forces brackets: x^y^z is illegal and latex requests you to manually put brackets: x^{y^z}. However, if you don’t want to force brackets and make the operator non-chainable (which python doesn’t do for any operators), right-associativity best matches what most people familiar with math notation will expect.

For more on why this convention was chosen, see:

i know. I was talking about: Operator associativity - Wikipedia
but the for an unknown reason the link disappeared in the discourse’s editor.

1 Like

If you know then why are you asking?

Because that’s how math works. You’ve also noticed it’s not just python but many other languages do the same. It’s because these languages don’t define this order, they just follow the mathematical convention.

because i find the solution just after asking :see_no_evil: