Operator Precedence

  • Operator Precedence in Python defines the hierarchy in which operators are evaluated in expressions. This lesson explains which operators are executed first and how Python applies associativity when multiple operators have the same level of precedence. 

  • Operator precedence defines the order in which operators are evaluated in an expression.

    Operators with higher precedence are evaluated before operators with lower precedence.

    If operators have the same precedence, Python follows associativity rules to decide the evaluation order.

    Operator Precedence Table (High → Low)

    Precedence Level

    Operator

    Description

    1 (Highest)

    ()

    Parentheses

    2

    **

    Exponentiation

    3

    + -

    Unary plus, unary minus

    4

    * / // %

    Multiplication, Division

    5

    + -

    Addition, Subtraction

    6

    > < >= <=

    Comparison

    7

    == !=

    Equality

    8

    not

    Logical NOT

    9

    and

    Logical AND

    10

    or

    Logical OR

    11 (Lowest)

    =

    Assignment

Operator Precedence Example

Demonstrates how Python evaluates expressions based on precedence.

result = 10 + 5 * 2
print(result)
  • Explanation:

    • * has higher precedence than +

    • So, 5 * 2 = 10

    • Then, 10 + 10 = 20

Using Parentheses

result = (10 + 5) * 2
print(result)
  • Explanation:

    • Parentheses are evaluated first

    • 10 + 5 = 15

    • 15 * 2 = 30

  • Associativity Rules

    Associativity decides the evaluation direction when two or more operators of the same precedence appear in an expression.

    Operator

    Associativity

    **

    Right to Left

    * / // %

    Left to Right

    + -

    Left to Right

    Comparison operators

    Left to Right

    Logical operators (and, or)

    Left to Right

    Assignment (=)

    Right to Left

Associativity

result = 2 ** 3 ** 2
print(result)
  • Explanation:

    • ** follows right-to-left associativity

    • So, 3 ** 2 = 9

    • Then, 2 ** 9 = 512