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.
Operators | Description |
---|---|
yield x | Generator function send protocol |
lambda args: expression | Anonymous function generation |
x if y else z | Ternary 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 x | Logical 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 | y | Bitwise OR, set union |
x ^ y | Bitwise XOR, set symmetric difference |
x & y | Bitwise AND, set intersection |
x << y, x >> y | Shift x left or right by y bits |
x + y | Addition, concatenation; |
x - y | Subtraction, set difference |
x * y | Multiplication, repetition; |
x % y | Remainder, format; |
x / y, x // y | Division: 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.