Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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
like image 773
StrixVaria Avatar asked Mar 04 '10 21:03

StrixVaria


People also ask

Which operator is right associative * *?

Right-associative operators of the same precedence are evaluated in order from right to left. For example, assignment is right-associative.

Is * right associative?

Associativity can be either Left to Right or Right to Left. For example: '*' and '/' have same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.

Which operator has left to right associativity in Python?

Python Operator Associativity Here the multiplication * and division / operators have left to right associativity.

Which has higher priority * or in Python?

Multiplication and both division operators have the same precedence, which is higher than addition and subtraction, which also have the same precedence.

Which operators have associativity right to left?

Explanation: Option 1: Unary Operators have associativity right to left in C++.

What is the associativity rules involved in this operator?

Operator Associativity We use associativity when two or more than two operators with the same precedence are present in the same expression. Example, The precedence of Division and Multiplication arithmetic operators is the same.


1 Answers

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

like image 73
Jimmy Avatar answered Sep 23 '22 05:09

Jimmy