lance wakeling net

Powers in Python


python, self-help

In Python the power operator can yield a surprising result if you expect it, as did I, to execute from left to right. The following expression evaluates to 🙀 False.

>>> -2 ** 2 == 4

From the docs:

The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right. The syntax is:

power ::= (await_expr | primary) [“**” u_expr]

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

For the expected result, parenthesize the left value (or use the pow() function).

>>> (-2)**2 == 4

>>> math.pow(-2, 2) == 4