Precedence and Associativity of Operators in Python

Precedence of Python Operators

The combination of values, variables, operators, and function calls is termed as an expression. The Python interpreter can evaluate a valid expression.

For example:

>>> 5 - 7
-2

Here 5 - 7 is an expression. There can be more than one operator in an expression.

To evaluate these types of expressions there is a rule of precedence in Python. It guides the order in which these operations are carried out.

For example, multiplication has higher precedence than subtraction.

# Multiplication has higher precedence
# than subtraction
>>> 10 - 4 * 2
2

But we can change this order using parentheses () as it has higher precedence than multiplication.

# Parentheses () has higher precedence
>>> (10 - 4) * 2
12

The operator precedence in Python is listed in the following table. It is in descending order (upper group has higher precedence than the lower ones).

Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
not Logical NOT