Associativity of Python Operators
Associativity aids in determining the sequence of operations when two operators
share the same priority.
The direction in which any given expression with more than one operator having
the same precedence is assessed is associativity. Almost every operator is
associative from left to right.
Code
# This shows Left to right associativity
print(4 * 9 // 3)
# Using parenthesis this time to show left to right associativity
print(4 * (9 // 3))
Output:
12
12
Note: In Python, the exponent operation ** possesses the right to left associativity.
Code
# This example demonstrates the right to left associativity of exponent
operator **
print (3 ** 2 ** 3)
# If we want to first solve 5 ** 7 then we can use ()
print ((3 ** 2) ** 3)
Output:
6561
729
Non Associative Operators
Several operators, such as comparison or assignment operators, don't have such
associativity rules in Python. Patterns of this type of operator have their own rules
that can not be represented as associativity. For instance, a < b < c is not the
same as (a < b) < c or a < (b < c). a < b < c is assessed from left to right and is
similar to a < b and b < c.
Additionally, while linking assignment operators such as a = b = c = 3 is entirely
acceptable, a = b = c += 2 is not acceptable.
Code
# Defining the variables a, b, and, c
a=b=c=3
#If the operator += follows associativity answer will shown otherwise
error will be raised
a = b = c += 2
Output:
a = b = c += 2
^
SyntaxError: invalid syntax
Hence, this operator does not follow left-to-right associativity.
The table below is showing associativity of various Python operators.
Operator Description Associativity
() Parentheses left to right
** Exponent right to left
*/% Multiplication / division / left to right
modulus
+- Addition / subtraction left to right
<< >> Bitwise left shift / Bitwise left to right
shift
< <= Relational operators: less left to right
less than or equal to / gre
> >= than / greater than or equ
== != Relational operators: is eq left to right
/ is not equal to
is, is not Identity operators left to right
in, not in Membership operators
& Bitwise AND operator left to right
^ Bitwise exclusive OR ope left to right
| Bitwise inclusive OR oper left to right
not Logical NOT right to left
and Logical AND left to right
or Logical OR left to right
= Assignment operators: right to left
+= -= Addition / subtraction
*= /= Multiplication / division
%= &= Modulus / bitwise AND
^= |= Bitwise exclusive / inclusiv
<<= >>= Bitwise shift left / right sh