Evaluation order and associativity

Evaluation order and associativity

In Python, evaluation order and associativity are determined by the operator precedence rules.

The operator precedence in Python follows the standard mathematical order of operations. Operators with higher precedence are evaluated before operators with lower precedence.

Here is the precedence order from highest to lowest:

  1. Parentheses: ()
  2. Exponentiation: **
  3. Unary operations: +, -, ~
  4. Multiplication, division, and remainder: *, /, %, //
  5. Addition and subtraction: +, –
  6. Bitwise left and right shift: <<, >>
  7. Bitwise AND: &
  8. Bitwise XOR: ^
  9. Bitwise OR: |
  10. Comparison operators: <, <=, >, >=, !=, ==
  11. Boolean NOT: not
  12. Boolean AND: and
  13. Boolean OR: or

The associativity of an operator determines the order in which operations with the same precedence are evaluated. In Python, most operators have left-to-right associativity, meaning that operations are evaluated from left to right.

However, exponentiation (**), bitwise shift operators (<< and >>), and ternary conditional operator (a if b else c) have right-to-left associativity. This means that operations with these operators are evaluated from right to left.

It is important to keep in mind the operator precedence and associativity while writing complex expressions in Python to ensure that the order of evaluation is as intended.

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

Share this post
[social_warfare]
Operators and expressions
The if statement

Get industry recognized certification – Contact us

keyboard_arrow_up