Python - Operator Operator precedence

Introduction

In Python, you code more complex expressions by combining operator expressions.

For instance, the sum of two multiplications might be written as a mix of variables and operators:

A * B + C * D 

The following table is ordered by operator precedence: Operators lower in the table have higher precedence.

OperatorsDescription
yield x Generator function send protocol
lambda args: expression Anonymous function generation
x if y else zTernary selection (x is evaluated only if y is true)
x or y Logical OR (y is evaluated only if x is false)
x and y Logical AND (y is evaluated only if x is true)
not xLogical negation
x in y, x not in y Membership (iterables, sets)
x is y, x is not y Object identity tests
x < y, x <= y, x > y, x >= y Magnitude comparison, set subset and super set;
x == y, x != y Value equality operators
x | yBitwise OR, set union
x ^ yBitwise XOR, set symmetric difference
x & yBitwise AND, set intersection
x << y, x >> y Shift x left or right by y bits
x + yAddition, concatenation;
x - ySubtraction, set difference
x * yMultiplication, repetition;
x % yRemainder, format;
x / y, x // yDivision: true and floor
-x, +x Negation, identity
~x Bitwise NOT (inversion)
x ** y Power (exponentiation)
x[i] Indexing (sequence, mapping, others)
x[i:j:k] Slicing
x(...) Call (function, method, class, other callable)
x.attr Attribute reference
(...)Tuple, expression, generator expression
[...]List, list comprehension
{...}Dictionary, set, set and dictionary comprehensions

Operators in the same row group from left to right when combined.

For example, if you write X + Y * Z, Python evaluates the multiplication first (Y * Z), then adds that result to X.

Related Topics