Precedence, Associativity of Operators, Non-Associative Operators

Precedence

OperatorDescriptionPrecedenceAssociativity
()ParenthesesHighestN/A
**ExponentiationHighRight-to-left
+x, -x, ~xUnary plus, Unary minus, Bitwise NOTHighRight-to-left
*, /, //, %Multiplication, Division, Floor division, ModulusMediumLeft-to-right
+, -Addition, SubtractionMediumLeft-to-right
<<, >>Bitwise shift operatorsMediumLeft-to-right
&Bitwise ANDMediumLeft-to-right
^Bitwise XORMediumLeft-to-right
``Bitwise ORMedium
==, !=, >, <, >=, <=, is, is not, in, not inComparisons, Identity, Membership operatorsLowLeft-to-right
notLogical NOTLowRight-to-left
andLogical ANDLowLeft-to-right
orLogical ORLowestLeft-to-right
=, +=, -=, *=, /=, etc.Assignment operatorsN/ANon-associative

    Associativity of Operators

    Associativity determines the order in which operators of the same precedence are evaluated. Most operators in Python have left-to-right associativity, meaning they are evaluated from left to right. However, some operators, like the exponentiation operator (**), have right-to-left associativity.

    Examples:

    • Left-to-right associativity:

      print(5 * 2 // 3)  # Output: 3
      

      Here, 5 * 2 is evaluated first, then the result is divided by 3.

    • Right-to-left associativity:

      print(2 ** 3 ** 2)  # Output: 512
      

      Here, 3 ** 2 is evaluated first, then 2 is raised to that power.

    Non-Associative Operators

    Non-associative operators cannot be chained together. In Python, the assignment operators (=, +=, etc.) are non-associative. This means you cannot write something like a = b = c = 5 and expect it to work as a single expression.


    Comments

    Popular posts from this blog

    Keyword , Identifier, Indentation, Comments & Documentation

    DSA Lab 8 program

    DSA Lab 7 Program