Why 2 ** 3 ** 4 is equal to 2 ** (3 ** 4)?

As title. Why for the power operator the precedence goes from right to left, instead that from left to right as for `+ -` and `* /` ?

Because that’s the precedence of exponentiation in mathematics: order of operations.

edit: That page makes a note that some languages do this differently, but I’m glad Python does it the way it works in mathematical notation.

2 Likes

In mathematical notation, `2 ** 3` is written as 2 with a superscript of 3, i.e. 2³, and `2 ** 3 ** 4` is written as 2 with a superscript of 3⁴ (which, unfortunately, I can’t write here).

This means that the `2 ** 3 ** 4` needs to be evaluated as `2 ** (3 ** 4)` in order to match what’s done in mathematical notation.

1 Like

`\$2^{3^4}\$` produces: 2^{3^4}

7 Likes

Thanks for that. I learned something new today.

Within the official Python documentation, currently representing version 3.12.1, see 6. Expressions, and within that page, go to the bottom to find 6.17. Operator precedence.

Note therein that conditional operators on the same precedence level, like exponentiation, also group from right to left:

Operators in the same box group left to right (except for exponentiation and conditional expressions, which group from right to left).

The Wikipedia article that @jamestwebber cited offers an interesting read, and notes that the rules vary somewhat among programming languages and software.

Thank you, written on paper is much more clear.

Markup Result
`\$2^3^4\$` 2^3^4
`\$2^{3^4}\$` 2^{3^4}
`\${2^3}^4\$` {2^3}^4
`\$(2^3)^4\$` (2^3)^4
`\$2^(3^4)\$` 2^(3^4)
`\$({2^3})^4\$` ({2^3})^4
`\$2^({3^4})\$` 2^({3^4})
`\${(2^3)}^4\$` {(2^3)}^4
`\$2^{(3^4)}\$` 2^{(3^4)}

Fascinating