An expression computes a value. This page covers each kind of expression, starting with the operator table, and follows chapter 6 of the Language Reference.
Operator precedence
The table runs from the most tightly binding to the least (6.17). Operators on one row have equal precedence. A row groups left to right unless the table says otherwise.
| Operators | Meaning | Grouping |
|---|---|---|
(...), [...], {key: value...}, {...} | Parenthesised expression, list, dictionary and set displays | |
x[i], x[i:j], x(args), x.attr | Subscription, slicing, call, attribute reference | Left to right |
await x | Await expression | |
** | Exponentiation | Right to left |
+x, -x, ~x | Positive, negative, bitwise NOT | |
*, @, /, //, % | Multiplication, matrix multiplication, division, floor division, remainder | Left to right |
+, - | Addition, subtraction | Left to right |
<<, >> | Shifts | Left to right |
& | Bitwise AND | Left to right |
^ | Bitwise XOR | Left to right |
| | Bitwise OR | Left to right |
in, not in, is, is not, <, <=, >, >=, !=, == | Comparisons, membership and identity tests | Chained |
not x | Boolean NOT | |
and | Boolean AND | Left to right |
or | Boolean OR | Left to right |
if – else | Conditional expression | Right to left |
lambda | Lambda expression | |
:= | Assignment expression |
** binds less tightly than a unary operator on its right, so
2 ** -1 is 0.5. It binds more tightly than a unary operator on its left,
so -2 ** 2 is -4 (6.5).
Atoms and displays
An atom is the most basic element: a name, a literal, a bracketed form or a display (6.2). A display builds a container from its items, evaluated left to right.
| Form | Result | Notes |
|---|---|---|
(a, b), a, b | Tuple | Commas make the tuple. () is the empty tuple |
[a, b] | List | |
{a, b} | Set | {} is an empty dictionary, not a set |
{k: v} | Dictionary | With duplicate keys, the last value wins |
(expr) | The value of expr | Grouping only, unless a comma is present |
... | Ellipsis |
Displays can unpack iterables and mappings into themselves (PEP 448, Python 3.5):
[*range(2), 2] # [0, 1, 2]
{*"ab", "c"} # a set of 'a', 'b', 'c'
{"x": 1, **{"y": 2}} # {'x': 1, 'y': 2}
(1, *[2, 3]) # (1, 2, 3)
Comprehensions
A comprehension builds a container by iterating and filtering (6.2.6):
comprehension: flexible_expression for_if_clause+
for_if_clause: ['async'] 'for' target_list 'in' or_test ('if' or_test)*
| Form | Result |
|---|---|
[x for x in it] | List |
{x for x in it} | Set |
{k: v for k, v in it} | Dictionary. The key is evaluated before the value (3.8) |
(x for x in it) | Generator expression |
Clauses read as nested statements, from left to right:
[n * m for n in (1, 2) if n for m in (3, 4)]
# does the same as
result = []
for n in (1, 2):
if n:
for m in (3, 4):
result.append(n * m)
for nests inside the one before it, and each if filtersThe comprehension has its
own scope. Inside an async def, async for and
await are allowed in comprehensions (PEP 530, Python 3.6).
Unpacking in comprehensions
Since Python 3.15 the expression of a list, set or generator comprehension can be
starred, and a dictionary comprehension can use ** (6.2.6.3, PEP
798).
lists = [[1, 2], [3]]
[*x for x in lists] # [1, 2, 3]
dicts = [{"a": 1}, {"a": 2, "b": 3}]
{**d for d in dicts} # {'a': 2, 'b': 3}: the last value wins
Generator expressions
A generator expression has the same clauses as a comprehension, in parentheses
(6.2.7). It returns a generator that produces values on demand, instead of building a
container. The parentheses can be left out if it is the only argument of a call, as in
sum(x * x for x in it).
The iterable of its leftmost for is evaluated at once, while everything
else waits until the generator is advanced. See
Generators.
Primaries
A primary is an atom followed by any number of attribute references, subscriptions and calls (6.3).
Attribute references
obj.name reads an attribute, through __getattribute__ and
descriptors, and
AttributeError is raised if it is missing. Inside a class,
private names are rewritten
first.
Subscriptions and slicing
proper_slice: [expression] ":" [expression] [":" [expression]]
s[i]calls__getitem__(i), and for a class,__class_getitem__.s[1:5:2]passes asliceobject as the key.s[1, 2]passes a tuple as the key, which NumPy uses.- A subscript can be starred:
s[*items](3.11, PEP 646). The items unpack into a tuple key.
Calls
f(positional, *iterable, keyword=value, **mapping)
Arguments may mix positional and keyword forms, with no positional form after a
keyword or **. * may follow a keyword but not **,
and any number of * and ** items may appear. A value is given to each
parameter as described on
Functions. A keyword written
twice is a SyntaxError, and one repeated through ** raises
TypeError. An object is callable if its type defines
__call__.
await
await_expr: "await" primary
Suspends a coroutine
until the awaited object is finished (6.4, PEP 492). It may be used only inside
async def. Its operand is a primary, so await -x is an
error.
Arithmetic operators
| Operator | Meaning and rules |
|---|---|
** | Power. A negative exponent on integers gives a float. 0 ** -1 raises ZeroDivisionError |
+x, -x, ~x | Unary positive, negative, bitwise inversion (~x is -x - 1) |
* | Product. A sequence and an integer repeat the sequence |
@ | Matrix multiplication (PEP 465). No built-in type implements it |
/ | Division, always a float for integers |
// | Floored quotient. See Types |
% | Remainder, with the sign of the right operand. On strings, printf-style formatting |
+, - | Sum and difference. + also joins sequences of the same type |
<<, >> | Shifts, by a count that must not be negative |
&, ^, | | Bitwise on integers. Sets use them for intersection, symmetric difference and union; | also merges dictionaries |
Operators on classes are defined by special methods.
Comparisons
comparison: or_expr (comp_operator or_expr)*
comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
| "is" ["not"] | ["not"] "in"
Comparisons chain (6.10). a < b <= c means
a < b and b <= c, with b evaluated once. The chain stops
at the first false result.
| Operator | Tests |
|---|---|
==, != | Equality of value. Objects of unrelated types are simply unequal |
<, <=, >, >= | Ordering. Unrelated types raise TypeError. Strings order by code point, and sequences order element by element |
in, not in | Membership. For a dictionary, its keys; for a string, a substring |
is, is not | Identity: whether they are the same object |
Use is only for singletons such as None. The compiler gives a
SyntaxWarning for is with a literal, as in
x is 1. Comparison behaviour is set by the
rich comparison methods.
Boolean operations
or_test: and_test | or_test "or" and_test
and_test: not_test | and_test "and" not_test
not_test: comparison | "not" not_test
and and or evaluate only as far as needed and return the
operand they stopped at, not a bool (6.11). not always
returns a bool. See Truth
values.
0 or "default" # 'default'
"a" or "b" # 'a'
"" and "b" # ''
1 and 2 # 2
not [] # True
or returns the first true operand, or the last oneAssignment expressions
assignment_expression: [identifier ":="] expression
The := operator binds a name and also gives the value (6.12, PEP 572,
Python 3.8). The target is a plain name, never an attribute or an item.
if (n := len(data)) > 10:
print(f"too long: {n}")
while chunk := read():
process(chunk)
An unparenthesised := is not valid as a statement on its own, as the
right-hand side of an assignment, or for a keyword argument's value. It is allowed
as a positional argument and in a list display, and in if and
while headers. Its scope in a comprehension is described under
Comprehension
scopes.
Conditional expressions
conditional_expression: or_test ["if" or_test "else" expression]
a if c else b evaluates c first, then only one of the other
two (6.13, PEP 308). It groups to the right, so
a if x else b if y else c means
a if x else (b if y else c).
Lambda expressions
lambda_expr: "lambda" [parameter_list] ":" expression
A lambda makes an anonymous function whose body is one expression, which
is returned (6.14). It accepts every
parameter kind, but it cannot have
statements or annotations. Its __name__ is <lambda>.
sorted(words, key=lambda w: (len(w), w))
Expression lists and unpacking
starred_expression: "*" or_expr | expression
flexible_expression: assignment_expression | starred_expression
An expression list with a comma makes a tuple (6.15). A starred item unpacks into the list. A trailing comma is allowed, and needed for a tuple of one. The bare forms are also how a function returns several values and how a tuple assignment works.
a = 1, 2 # (1, 2)
b = *a, 3 # (1, 2, 3)
c = (5,) # one-item tuple
d = (5) # the integer 5
Evaluation order
Python evaluates expressions from left to right (6.16). In an assignment, the right-hand side is evaluated before the left. In these lines, the subexpressions are evaluated in the order of their numbers:
expr1, expr2, expr3, expr4
{expr1: expr2, expr3: expr4}
expr1 + expr2 * (expr3 - expr4)
expr1(expr2, expr3, *expr4, **expr5)
expr3, expr4 = expr1, expr2