Precedence, Associativity of Operators, Non-Associative Operators
Precedence
| Operator | Description | Precedence | Associativity |
|---|---|---|---|
() | Parentheses | Highest | N/A |
** | Exponentiation | High | Right-to-left |
+x, -x, ~x | Unary plus, Unary minus, Bitwise NOT | High | Right-to-left |
*, /, //, % | Multiplication, Division, Floor division, Modulus | Medium | Left-to-right |
+, - | Addition, Subtraction | Medium | Left-to-right |
<<, >> | Bitwise shift operators | Medium | Left-to-right |
& | Bitwise AND | Medium | Left-to-right |
^ | Bitwise XOR | Medium | Left-to-right |
| ` | ` | Bitwise OR | Medium |
==, !=, >, <, >=, <=, is, is not, in, not in | Comparisons, Identity, Membership operators | Low | Left-to-right |
not | Logical NOT | Low | Right-to-left |
and | Logical AND | Low | Left-to-right |
or | Logical OR | Lowest | Left-to-right |
=, +=, -=, *=, /=, etc. | Assignment operators | N/A | Non-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.
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.
Left-to-right associativity:
print(5 * 2 // 3) # Output: 3Here,
5 * 2is evaluated first, then the result is divided by3.Right-to-left associativity:
print(2 ** 3 ** 2) # Output: 512Here,
3 ** 2is evaluated first, then2is 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.
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
Post a Comment