1 min read

Python Operator Precedence

Operator precedence determines the order in which operations are performed in an expression. Operators with higher precedence are performed before operators with lower precedence.

Precedence Table

The following table lists all operators from highest precedence to lowest.

Operator Description
() Parentheses (grouping)
f(args...), x[index:index], x[index], x.attribute Function call, slicing, subscription, attribute reference
await x Await expression
** Exponentiation
+x, -x, ~x Positive, negative, bitwise NOT
*, @, /, //, % Multiplication, matrix multiplication, division, floor division, remainder
+, - Addition and subtraction
<<, >> Bitwise shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
in, not in, is, is not, <, <=, >, >=, !=, == Comparisons, including membership tests and identity tests
not x Boolean NOT
and Boolean AND
or Boolean OR
ifelse Conditional expression
lambda Lambda expression
:= Assignment expression (walrus operator)

Associativity

Most operators in Python are left-associative, meaning that if an expression contains multiple operators with the same precedence, they are evaluated from left to right.

print(10 - 4 - 3) 
# Output: 3
# Calculated as (10 - 4) - 3

Exponentiation ** is right-associative.

print(2 ** 3 ** 2)
# Output: 512
# Calculated as 2 ** (3 ** 2) -> 2 ** 9

Examples

Multiplication has higher precedence than addition

x = 10 + 3 * 2
print(x) # Output: 16 (10 + 6)

Parentheses override precedence

x = (10 + 3) * 2
print(x) # Output: 26 (13 * 2)

programming/python/python