What is the associativity of Python's ** operator?

2** (2**(2**2))

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

Operators in the same box group left to right (except for comparisons, including tests, which all have the same precedence and chain from left to right — see section Comparisons — and exponentiation, which groups from right to left).


Either it associates to the left or the right. To discover the answer yourself, do the experiment.

>>> 3 ** 3 ** 3
7625597484987
>>> (3 ** 3) ** 3
19683
>>> 3 ** (3 ** 3)
7625597484987

Thus, it associates to the right.

Or you can read the docs. google: "python power" and the first result is http://www.python.org/doc/2.5.2/ref/power.html

The second sentence is:

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).

Confirming the experimental results.

Tags:

Python