Home / Questions / What is the precedence of operators in Python?
Explanatory Question

What is the precedence of operators in Python?

👁 312 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

  • Operator precedence refers to the order in which Python evaluates operators in an expression.
  • The precedence of operators in Python is determined by their priority or hierarchy, which specifies which operators should be evaluated first in an expression.
  • For example, multiplication and division have a higher priority than addition and subtraction, so they will be evaluated first in an expression that contains both types of operators.
  • Operators with higher precedence are evaluated before operators with lower precedence.
  • If operators have the same precedence, then their evaluation order is determined by their associativity, which specifies whether the operators are evaluated from left to right or from right to left.
  • The table below shows the precedence of operators in Python, from highest to lowest:
Precedence Operator Description
1 () Parentheses (grouping)
2 +x, -x Positive, negative
3 ** Exponentiation
4 *, /, //, % Multiplication, division, floor division, modulus
5 +, - Addition, subtraction
6 <<, >> Bitwise shift operators
7 & Bitwise AND
8 ^ Bitwise XOR
9 | Bitwise OR
10 <, <=, >, >= Comparison operators
11 ==, != Equality operators
12 not Logical NOT
13 and Logical AND
14 or Logical OR
15 if else Conditional expression
16 =, +=, -=, *=, /=, //=, %=, &=, ^=, |=, <<=, >>= Assignment operators
  • The above table shows the most commonly used operators in Python, but there are additional operators that have different precedence levels based on their type and use-case.
  • It's important to be aware of operator precedence when writing complex expressions to ensure that the order of operations is correct and produces the desired result.