tags:

views:

110

answers:

4

I was just playing around with the python command line and the ** operator, which as far as I know performs a power function. So 2 ** 3 should be (and is) 8 because 2 * 2 * 2 = 8.

Can someone explain the behavior I found? I don't see any way to group the operations with parentheses to actually get a result of 65536 like was attained here.

>>> 2 ** 2 ** 2
16
>>> 2 ** 2 ** 2 ** 2
65536
>>> (2 ** 2 ** 2) ** 2
256
+5  A: 
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).

Jimmy
A: 

Also:

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

One way or the other, it becomes 2 ** 16

GreenMatt
A: 

The ** operator is right associative:

2 ** (2 ** (2 ** 2)) = 2 ** (2 ** 4) = 2 ** 16 = 65536

Nick
+2  A: 

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.

Paul Hankin