Skip to main content

Expressions

An expression produces a value. This page enumerates every expression form, the rules that govern evaluation order, and the operator precedence that determines parse tree shape.

Source-of-record: CPython expressions, Python/compile.c (codegen), Python/bytecodes.c (semantics).

Atoms

AtomProduces
NAMEResult of name lookup (see Execution model).
NUMBERint, float, or complex.
STRINGstr, bytes, f-string result, or t"" template.
True / False / NoneThe singletons.
... (Ellipsis)The singleton.
(...)Grouped expression or tuple.
[...]List display or list comprehension.
{...}Set, set comprehension, dict, or dict comprehension.

Tuple displays

FormResult
()Empty tuple.
(x,)One-element tuple.
(x, y)Tuple (x, y).
(x)Just x (grouping, not a tuple).

List, set, dict displays

FormType
[a, b, c]list.
{a, b, c}set.
{a: b, c: d}dict.
{}Empty dict.
set()Empty set (no literal).
[a for a in x]List comprehension.
{a for a in x}Set comprehension.
{a: b for a in x}Dict comprehension.
(a for a in x)Generator expression.

Generator expressions

Generator expressions evaluate the leftmost for clause's iterator eagerly; everything else is lazy. The generator function's frame suspends at each yield.

Primaries

Primaries follow an atom and apply operations to it.

PrimaryFormSource slot/operation
Attributex.name__getattribute__ / __getattr__.
Subscriptionx[key]__getitem__.
Slicingx[a:b:c]__getitem__(slice(a, b, c)).
Callx(args)__call__ via tp_call.

Slicing is sugar for constructing a slice object and passing it to __getitem__. Extended slicing x[a:b, c:d] builds a tuple of slice objects.

Operator precedence

From lowest to highest binding:

PrecedenceOperatorAssociativity
1lambda-
2ifelse conditionalright
3orleft
4andleft
5not x-
6in, not in, is, is not, <, <=, >, >=, !=, ==left
7|left
8^left
9&left
10<<, >>left
11+, -left
12*, @, /, //, %left
13+x, -x, ~x (unary)-
14**right
15await x-
16x[i], x.attr, x(...)left
17(...), [...], {...}, atom-

The walrus := lives outside this table; it is allowed only in specific syntactic positions, never at statement top level.

Boolean operations

Short-circuit:

ExpressionReturns
x or yx if bool(x) else y. Does not coerce to bool.
x and yx if not bool(x) else y.
not xFalse if bool(x) else True. Always a bool.

Comparisons

Comparison expressions can be chained: a < b < c desugars to a < b and b < c, but b is evaluated only once.

OperatorMethodNotes
<__lt__, reflected __gt__
<=__le__, reflected __ge__
==__eq__, reflected __eq__Default: identity.
!=__ne__, reflected __ne__Default: not (x == y).
>__gt__, reflected __lt__
>=__ge__, reflected __le__
is / is not-Identity. Not method-overridable.
in / not in__contains__Falls back to iteration.

For numeric comparison, mixed types are coerced according to the numeric tower (int, float, complex). Equality across types that are not numerically related returns False.

Arithmetic and bitwise operators

All arithmetic and bitwise operators go through forward and reflected dunder lookup as described in Special methods.

Numeric semantics

OperatorInteger behaviourFloat behaviour
+, -Exact arbitrary precisionIEEE 754
*ExactIEEE 754
/True division -> floatIEEE 754
//Floor divisionmath.floor of true division
%Floor modulo: sign of divisorIEEE remainder for floats
**Exact for non-negative exponentIEEE 754, special cases per math.pow
divmod(a // b, a % b)Same

Bitwise semantics

int is treated as two's complement of infinite width. x & y, x | y, x ^ y operate bitwise. x << n raises ValueError for negative n. ~x is -(x + 1).

Sequence and mapping operations

OperationSequencesMappings
x[i]Element at index i.Value for key i.
x[i:j] / x[i:j:k]Slice.-
len(x)Length.Number of items.
x + yConcatenation.-
x * nRepetition.-
y in xContainment (linear scan).Key membership.

Conditional expression

x if c else y

Evaluates c. If truthy, evaluates and returns x. Else evaluates and returns y. The unselected branch is not evaluated.

Lambda

lambda params: expression

A lambda is an unnamed function expression. Body is a single expression (no statements). Same parameter syntax as def.

Yield expressions

FormEffect
yieldYields None. Returns the value sent or None.
yield valueYields value. Returns the value sent.
yield from iterDelegates to a sub-iterator.

yield from g is roughly equivalent to:

for x in g:
yield x

but it also forwards send, throw, and close.

await expr is a related coroutine-only form; see Compound statements -> async.

Assignment expression (walrus)

x := value

Binds value to x in the enclosing scope (or the comprehension's hidden scope if used inside one). Allowed positions:

Allowed inNot allowed in
if/while conditionTop-level expression statement
Comprehension if and outer iterablelambda parameter default
Function-call argumentFunction-def parameter default
SubscriptAugmented assignment target

Starred expression

*expr and **expr appear in:

ContextMeaning
Function callSplat into positional / keyword.
Function def paramsVariadic positional / variadic keyword.
Tuple/list displayUnpack iterable into the display.
Dict displayUnpack mapping into the display.
Assignment targetCollect remaining elements into a list (PEP 3132).

Comprehension scoping

A comprehension creates its own scope. The leftmost iterable is evaluated in the enclosing scope; everything else is in the comprehension's scope. The walrus := inside a comprehension writes to the enclosing scope, not the comprehension scope.

F-string expressions

ElementMeaning
{expr}format(expr, '').
{expr!r} / {expr!s} / {expr!a}Apply repr / str / ascii first.
{expr:format_spec}Pass format_spec to __format__.
{expr=}Emit expr=<repr> for debugging.
{{ / }}Literal brace.

Any expression is allowed inside {...} since PEP 701, including backslashes, line breaks, and nested f-strings.

Evaluation order

Python evaluates operands left to right with these exceptions:

ConstructOrder
Assignment lhs = rhsrhs first, then lhs targets.
Comparison chain a < b < ca, b, then b < c. b evaluated once.
x if c else yc first, then x or y.
x or y / x and yx first, then y only if needed.
Function call f(x, y, z)f, then x, y, z in order; keyword args after positional.

Reference