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

前端 未结 4 1346
自闭症患者
自闭症患者 2020-12-11 04:21

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 *

相关标签:
4条回答
  • The ** operator is right associative:

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

    0 讨论(0)
  • 2020-12-11 05:07
    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).

    0 讨论(0)
  • 2020-12-11 05:14

    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.

    0 讨论(0)
  • 2020-12-11 05:14

    Also:

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

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

    This is following standard mathematical operations, where: 234 becomes 2 81, instead of 84 and thus is 2417851639229258349412352, instead of 4096.

    0 讨论(0)
提交回复
热议问题