Cover Image for Precedence and Associativity of Operators in Python
240 views

Precedence and Associativity of Operators in Python

The Python operators have a predefined precedence and associativity, which determine the order in which operators are evaluated in an expression. Understanding operator precedence and associativity is essential for writing correct and predictable code.

Here’s a summary of some of the key operators in Python, along with their precedence levels and associativity:

  1. Parentheses ():
  • Highest precedence
  • Associativity: Left-to-right
  • Parentheses are used to group expressions and override the default operator precedence.
  1. Exponentiation **:
  • Second highest precedence
  • Associativity: Right-to-left
  • Used for raising a number to a power.
  1. Negation - (Unary):
  • Next in precedence after exponentiation
  • Associativity: Right-to-left
  • Unary negation (e.g., -x) is applied to a single operand.
  1. Multiplication *, Division /, Floor Division //, and Modulus %:
  • Same precedence level
  • Associativity: Left-to-right
  • These operators perform multiplication, division, floor division (integer division), and remainder operations.
  1. Addition + and Subtraction -:
  • Same precedence level
  • Associativity: Left-to-right
  • These operators perform addition and subtraction.
  1. Bitwise Shifts << and >>:
  • Same precedence level
  • Associativity: Left-to-right
  • These operators perform bitwise left and right shifts.
  1. Bitwise AND &:
  • Same precedence level
  • Associativity: Left-to-right
  • Performs bitwise AND between integers.
  1. Bitwise XOR ^:
  • Same precedence level
  • Associativity: Left-to-right
  • Performs bitwise XOR between integers.
  1. Bitwise OR |:
  • Same precedence level
  • Associativity: Left-to-right
  • Performs bitwise OR between integers.
  1. Comparison Operators (<, <=, >, >=, ==, !=):
    • Same precedence level
    • Associativity: Left-to-right
    • These operators compare values and return Boolean results.
  2. Boolean NOT not:
    • Next in precedence after comparison operators
    • Associativity: Right-to-left
    • Used to negate a Boolean value.
  3. Boolean AND and:
    • Next in precedence after not
    • Associativity: Left-to-right
    • Used to perform Boolean AND between values.
  4. Boolean OR or:
    • Lowest precedence
    • Associativity: Left-to-right
    • Used to perform Boolean OR between values.

It’s essential to be aware of operator precedence and associativity to avoid unexpected results in expressions. When in doubt, you can use parentheses to explicitly specify the order of evaluation in complex expressions. For example, (a + b) * c ensures that addition is performed before multiplication, regardless of the default precedence.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS