Operator Precedence

suggest change

Introduction

Python operators have a set order of precedence, which determines what operators are evaluated first in a potentially ambiguous expression. For instance, in the expression 3 * 2 + 7, first 3 is multiplied by 2, and then the result is added to 7, yielding 13. The expression is not evaluated the other way around, because * has a higher precedence than +.

Below is a list of operators by precedence, and a brief description of what they (usually) do.

Remarks

From the Python documentation:

The following table summarizes the operator precedence in Python, from highest precedence (most binding) to lowest precedence (least binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for exponentiation and conditional expressions, which group from right to left).

Comparisons, membership tests, and identity tests all have the same precedence and chain from left to right. <> is not a Python 3 operator, and backtick string conversion is not part of this table.

Operator Description
(expressions...), [expressions...], {key: value...}, {expressions...} Binding or parenthesized expression, list display, dictionary display, set display
x[index], x[index:index], x(arguments...), x.attribute Subscription, slicing, call, attribute reference
await x Await expression
** Exponentiation [5]
+x, -x, ~x Positive, negative, bitwise NOT
*, @, /, //, % Multiplication, matrix multiplication, division, floor division, remainder [6]
+, - Addition and subtraction
<<, >> 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
if – else Conditional expression
lambda Lambda expression
:= Assignment expression

[5] The power operator ** binds less tightly than an arithmetic or bitwise unary operator on its right, so 2**-1 is 0.5.

[6] The % operator is also used for string formatting; the same precedence applies.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents