Hướng dẫn hàm any() trong python

Syntax Notes: In this and the following chapters, extended BNF notation will be used to describe syntax, not lexical analysis. When (one alternative of) a syntax rule has the form

name ::=  othername

and no semantics are given, the semantics of this form of

parenth_form ::=  "(" [starred_expression] ")"
4 are the same as for
parenth_form ::=  "(" [starred_expression] ")"
5.

6.1. Arithmetic conversions¶

When a description of an arithmetic operator below uses the phrase “the numeric arguments are converted to a common type”, this means that the operator implementation for built-in types works as follows:

  • If either argument is a complex number, the other is converted to complex;

  • otherwise, if either argument is a floating point number, the other is converted to floating point;

  • otherwise, both must be integers and no conversion is necessary.

Some additional rules apply for certain operators (e.g., a string as a left argument to the ‘%’ operator). Extensions must define their own conversion behavior.

6.2. Atoms¶

Atoms are the most basic elements of expressions. The simplest atoms are identifiers or literals. Forms enclosed in parentheses, brackets or braces are also categorized syntactically as atoms. The syntax for atoms is:

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom

6.2.1. Identifiers (Names)¶

An identifier occurring as an atom is a name. See section Identifiers and keywords for lexical definition and section Naming and binding for documentation of naming and binding.

When the name is bound to an object, evaluation of the atom yields that object. When a name is not bound, an attempt to evaluate it raises a

parenth_form ::=  "(" [starred_expression] ")"
6 exception.

Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name, with leading underscores removed and a single underscore inserted, in front of the name. For example, the identifier

parenth_form ::=  "(" [starred_expression] ")"
7 occurring in a class named
parenth_form ::=  "(" [starred_expression] ")"
8 will be transformed to
parenth_form ::=  "(" [starred_expression] ")"
9. This transformation is independent of the syntactical context in which the identifier is used. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done.

6.2.2. Literals¶

Python supports string and bytes literals and various numeric literals:

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber

Evaluation of a literal yields an object of the given type (string, bytes, integer, floating point number, complex number) with the given value. The value may be approximated in the case of floating point and imaginary (complex) literals. See section Literals for details.

All literals correspond to immutable data types, and hence the object’s identity is less important than its value. Multiple evaluations of literals with the same value (either the same occurrence in the program text or a different occurrence) may obtain the same object or a different object with the same value.

6.2.3. Parenthesized forms¶

A parenthesized form is an optional expression list enclosed in parentheses:

parenth_form ::=  "(" [starred_expression] ")"

A parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list.

An empty pair of parentheses yields an empty tuple object. Since tuples are immutable, the same rules as for literals apply (i.e., two occurrences of the empty tuple may or may not yield the same object).

Note that tuples are not formed by the parentheses, but rather by use of the comma. The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.

6.2.4. Displays for lists, sets and dictionaries¶

For constructing a list, a set or a dictionary Python provides special syntax called “displays”, each of them in two flavors:

  • either the container contents are listed explicitly, or

  • they are computed via a set of looping and filtering instructions, called a comprehension.

Common syntax elements for comprehensions are:

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]

The comprehension consists of a single expression followed by at least one

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
0 clause and zero or more
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
0 or
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
2 clauses. In this case, the elements of the new container are those that would be produced by considering each of the
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
0 or
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
2 clauses a block, nesting from left to right, and evaluating the expression to produce an element each time the innermost block is reached.

However, aside from the iterable expression in the leftmost

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
0 clause, the comprehension is executed in a separate implicitly nested scope. This ensures that names assigned to in the target list don’t “leak” into the enclosing scope.

The iterable expression in the leftmost

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
0 clause is evaluated directly in the enclosing scope and then passed as an argument to the implicitly nested scope. Subsequent
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
0 clauses and any filter condition in the leftmost
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
0 clause cannot be evaluated in the enclosing scope as they may depend on the values obtained from the leftmost iterable. For example:
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
9.

To ensure the comprehension always results in a container of the appropriate type,

list_display ::=  "[" [starred_list | comprehension] "]"
0 and
list_display ::=  "[" [starred_list | comprehension] "]"
1 expressions are prohibited in the implicitly nested scope.

Since Python 3.6, in an

list_display ::=  "[" [starred_list | comprehension] "]"
2 function, an
list_display ::=  "[" [starred_list | comprehension] "]"
3 clause may be used to iterate over a asynchronous iterator. A comprehension in an
list_display ::=  "[" [starred_list | comprehension] "]"
2 function may consist of either a
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
0 or
list_display ::=  "[" [starred_list | comprehension] "]"
3 clause following the leading expression, may contain additional
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
0 or
list_display ::=  "[" [starred_list | comprehension] "]"
3 clauses, and may also use
list_display ::=  "[" [starred_list | comprehension] "]"
9 expressions. If a comprehension contains either
list_display ::=  "[" [starred_list | comprehension] "]"
3 clauses or
list_display ::=  "[" [starred_list | comprehension] "]"
9 expressions or other asynchronous comprehensions it is called an asynchronous comprehension. An asynchronous comprehension may suspend the execution of the coroutine function in which it appears. See also PEP 530.

New in version 3.6: Asynchronous comprehensions were introduced.

Changed in version 3.8:

list_display ::=  "[" [starred_list | comprehension] "]"
0 and
list_display ::=  "[" [starred_list | comprehension] "]"
1 prohibited in the implicitly nested scope.

Changed in version 3.11: Asynchronous comprehensions are now allowed inside comprehensions in asynchronous functions. Outer comprehensions implicitly become asynchronous.

6.2.5. List displays¶

A list display is a possibly empty series of expressions enclosed in square brackets:

list_display ::=  "[" [starred_list | comprehension] "]"

A list display yields a new list object, the contents being specified by either a list of expressions or a comprehension. When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and placed into the list object in that order. When a comprehension is supplied, the list is constructed from the elements resulting from the comprehension.

6.2.6. Set displays¶

A set display is denoted by curly braces and distinguishable from dictionary displays by the lack of colons separating keys and values:

set_display ::=  "{" (starred_list | comprehension) "}"

A set display yields a new mutable set object, the contents being specified by either a sequence of expressions or a comprehension. When a comma-separated list of expressions is supplied, its elements are evaluated from left to right and added to the set object. When a comprehension is supplied, the set is constructed from the elements resulting from the comprehension.

An empty set cannot be constructed with

set_display ::=  "{" (starred_list | comprehension) "}"
4; this literal constructs an empty dictionary.

6.2.7. Dictionary displays¶

A dictionary display is a possibly empty series of key/datum pairs enclosed in curly braces:

dict_display       ::=  "{" [key_datum_list | dict_comprehension] "}"
key_datum_list     ::=  key_datum ("," key_datum)* [","]
key_datum          ::=  expression ":" expression | "**" or_expr
dict_comprehension ::=  expression ":" expression comp_for

A dictionary display yields a new dictionary object.

If a comma-separated sequence of key/datum pairs is given, they are evaluated from left to right to define the entries of the dictionary: each key object is used as a key into the dictionary to store the corresponding datum. This means that you can specify the same key multiple times in the key/datum list, and the final dictionary’s value for that key will be the last one given.

A double asterisk

set_display ::=  "{" (starred_list | comprehension) "}"
5 denotes dictionary unpacking. Its operand must be a mapping. Each mapping item is added to the new dictionary. Later values replace values already set by earlier key/datum pairs and earlier dictionary unpackings.

New in version 3.5: Unpacking into dictionary displays, originally proposed by PEP 448.

A dict comprehension, in contrast to list and set comprehensions, needs two expressions separated with a colon followed by the usual “for” and “if” clauses. When the comprehension is run, the resulting key and value elements are inserted in the new dictionary in the order they are produced.

Restrictions on the types of the key values are listed earlier in section The standard type hierarchy. (To summarize, the key type should be hashable, which excludes all mutable objects.) Clashes between duplicate keys are not detected; the last datum (textually rightmost in the display) stored for a given key value prevails.

Changed in version 3.8: Prior to Python 3.8, in dict comprehensions, the evaluation order of key and value was not well-defined. In CPython, the value was evaluated before the key. Starting with 3.8, the key is evaluated before the value, as proposed by PEP 572.

6.2.8. Generator expressions¶

A generator expression is a compact generator notation in parentheses:

generator_expression ::=  "(" expression comp_for ")"

A generator expression yields a new generator object. Its syntax is the same as for comprehensions, except that it is enclosed in parentheses instead of brackets or curly braces.

Variables used in the generator expression are evaluated lazily when the

set_display ::=  "{" (starred_list | comprehension) "}"
6 method is called for the generator object (in the same fashion as normal generators). However, the iterable expression in the leftmost
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
0 clause is immediately evaluated, so that an error produced by it will be emitted at the point where the generator expression is defined, rather than at the point where the first value is retrieved. Subsequent
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
0 clauses and any filter condition in the leftmost
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
0 clause cannot be evaluated in the enclosing scope as they may depend on the values obtained from the leftmost iterable. For example:
dict_display       ::=  "{" [key_datum_list | dict_comprehension] "}"
key_datum_list     ::=  key_datum ("," key_datum)* [","]
key_datum          ::=  expression ":" expression | "**" or_expr
dict_comprehension ::=  expression ":" expression comp_for
0.

The parentheses can be omitted on calls with only one argument. See section Calls for details.

To avoid interfering with the expected operation of the generator expression itself,

list_display ::=  "[" [starred_list | comprehension] "]"
0 and
list_display ::=  "[" [starred_list | comprehension] "]"
1 expressions are prohibited in the implicitly defined generator.

If a generator expression contains either

list_display ::=  "[" [starred_list | comprehension] "]"
3 clauses or
list_display ::=  "[" [starred_list | comprehension] "]"
9 expressions it is called an asynchronous generator expression. An asynchronous generator expression returns a new asynchronous generator object, which is an asynchronous iterator (see Asynchronous Iterators).

New in version 3.6: Asynchronous generator expressions were introduced.

Changed in version 3.7: Prior to Python 3.7, asynchronous generator expressions could only appear in

list_display ::=  "[" [starred_list | comprehension] "]"
2 coroutines. Starting with 3.7, any function can use asynchronous generator expressions.

Changed in version 3.8:

list_display ::=  "[" [starred_list | comprehension] "]"
0 and
list_display ::=  "[" [starred_list | comprehension] "]"
1 prohibited in the implicitly nested scope.

6.2.9. Yield expressions¶

yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]

The yield expression is used when defining a generator function or an asynchronous generator function and thus can only be used in the body of a function definition. Using a yield expression in a function’s body causes that function to be a generator function, and using it in an

list_display ::=  "[" [starred_list | comprehension] "]"
2 function’s body causes that coroutine function to be an asynchronous generator function. For example:

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
0

Due to their side effects on the containing scope,

list_display ::=  "[" [starred_list | comprehension] "]"
0 expressions are not permitted as part of the implicitly defined scopes used to implement comprehensions and generator expressions.

Changed in version 3.8: Yield expressions prohibited in the implicitly nested scopes used to implement comprehensions and generator expressions.

Generator functions are described below, while asynchronous generator functions are described separately in section Asynchronous generator functions.

When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of the generator function. The execution starts when one of the generator’s methods is called. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of

generator_expression ::=  "(" expression comp_for ")"
0 to the generator’s caller. By suspended, we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. When the execution is resumed by calling one of the generator’s methods, the function can proceed exactly as if the yield expression were just another external call. The value of the yield expression after resuming depends on the method which resumed the execution. If
set_display ::=  "{" (starred_list | comprehension) "}"
6 is used (typically via either a
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
0 or the
generator_expression ::=  "(" expression comp_for ")"
3 builtin) then the result is
generator_expression ::=  "(" expression comp_for ")"
4. Otherwise, if
generator_expression ::=  "(" expression comp_for ")"
5 is used, then the result will be the value passed in to that method.

All of this makes generator functions quite similar to coroutines; they yield multiple times, they have more than one entry point and their execution can be suspended. The only difference is that a generator function cannot control where the execution should continue after it yields; the control is always transferred to the generator’s caller.

Yield expressions are allowed anywhere in a

generator_expression ::=  "(" expression comp_for ")"
6 construct. If the generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), the generator-iterator’s
generator_expression ::=  "(" expression comp_for ")"
7 method will be called, allowing any pending
generator_expression ::=  "(" expression comp_for ")"
8 clauses to execute.

When

generator_expression ::=  "(" expression comp_for ")"
9 is used, the supplied expression must be an iterable. The values produced by iterating that iterable are passed directly to the caller of the current generator’s methods. Any values passed in with
generator_expression ::=  "(" expression comp_for ")"
5 and any exceptions passed in with
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
1 are passed to the underlying iterator if it has the appropriate methods. If this is not the case, then
generator_expression ::=  "(" expression comp_for ")"
5 will raise
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
3 or
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
4, while
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
1 will just raise the passed in exception immediately.

When the underlying iterator is complete, the

yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
6 attribute of the raised
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
7 instance becomes the value of the yield expression. It can be either set explicitly when raising
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
7, or automatically when the subiterator is a generator (by returning a value from the subgenerator).

Changed in version 3.3: Added

generator_expression ::=  "(" expression comp_for ")"
9 to delegate control flow to a subiterator.

The parentheses may be omitted when the yield expression is the sole expression on the right hand side of an assignment statement.

See also

PEP 255 - Simple Generators

The proposal for adding generators and the

list_display ::=  "[" [starred_list | comprehension] "]"
0 statement to Python.

PEP 342 - Coroutines via Enhanced Generators

The proposal to enhance the API and syntax of generators, making them usable as simple coroutines.

PEP 380 - Syntax for Delegating to a Subgenerator

The proposal to introduce the

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
01 syntax, making delegation to subgenerators easy.

PEP 525 - Asynchronous Generators

The proposal that expanded on PEP 492 by adding generator capabilities to coroutine functions.

6.2.9.1. Generator-iterator methods¶

This subsection describes the methods of a generator iterator. They can be used to control the execution of a generator function.

Note that calling any of the generator methods below when the generator is already executing raises a

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
02 exception.

generator.__next__()

Starts the execution of a generator function or resumes it at the last executed yield expression. When a generator function is resumed with a

set_display ::=  "{" (starred_list | comprehension) "}"
6 method, the current yield expression always evaluates to
generator_expression ::=  "(" expression comp_for ")"
4. The execution then continues to the next yield expression, where the generator is suspended again, and the value of the
generator_expression ::=  "(" expression comp_for ")"
0 is returned to
set_display ::=  "{" (starred_list | comprehension) "}"
6’s caller. If the generator exits without yielding another value, a
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
7 exception is raised.

This method is normally called implicitly, e.g. by a

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
0 loop, or by the built-in
generator_expression ::=  "(" expression comp_for ")"
3 function.

generator.send(value)

Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The

generator_expression ::=  "(" expression comp_for ")"
5 method returns the next value yielded by the generator, or raises
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
7 if the generator exits without yielding another value. When
generator_expression ::=  "(" expression comp_for ")"
5 is called to start the generator, it must be called with
generator_expression ::=  "(" expression comp_for ")"
4 as the argument, because there is no yield expression that could receive the value.

generator.throw(value)generator.throw(type[, value[, traceback]])

Raises an exception at the point where the generator was paused, and returns the next value yielded by the generator function. If the generator exits without yielding another value, a

yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
7 exception is raised. If the generator function does not catch the passed-in exception, or raises a different exception, then that exception propagates to the caller.

In typical use, this is called with a single exception instance similar to the way the

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
15 keyword is used.

For backwards compatibility, however, the second signature is supported, following a convention from older versions of Python. The type argument should be an exception class, and value should be an exception instance. If the value is not provided, the type constructor is called to get an instance. If traceback is provided, it is set on the exception, otherwise any existing

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
16 attribute stored in value may be cleared.

generator.close()

Raises a

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
17 at the point where the generator function was paused. If the generator function then exits gracefully, is already closed, or raises
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
17 (by not catching the exception), close returns to its caller. If the generator yields a value, a
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
19 is raised. If the generator raises any other exception, it is propagated to the caller.
generator_expression ::=  "(" expression comp_for ")"
7 does nothing if the generator has already exited due to an exception or normal exit.

6.2.9.2. Examples¶

Here is a simple example that demonstrates the behavior of generators and generator functions:

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
1

For examples using

list_display ::=  "[" [starred_list | comprehension] "]"
1, see PEP 380: Syntax for Delegating to a Subgenerator in “What’s New in Python.”

6.2.9.3. Asynchronous generator functions¶

The presence of a yield expression in a function or method defined using

list_display ::=  "[" [starred_list | comprehension] "]"
2 further defines the function as an asynchronous generator function.

When an asynchronous generator function is called, it returns an asynchronous iterator known as an asynchronous generator object. That object then controls the execution of the generator function. An asynchronous generator object is typically used in an

list_display ::=  "[" [starred_list | comprehension] "]"
3 statement in a coroutine function analogously to how a generator object would be used in a
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
0 statement.

Calling one of the asynchronous generator’s methods returns an awaitable object, and the execution starts when this object is awaited on. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of

generator_expression ::=  "(" expression comp_for ")"
0 to the awaiting coroutine. As with a generator, suspension means that all local state is retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. When the execution is resumed by awaiting on the next object returned by the asynchronous generator’s methods, the function can proceed exactly as if the yield expression were just another external call. The value of the yield expression after resuming depends on the method which resumed the execution. If
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
26 is used then the result is
generator_expression ::=  "(" expression comp_for ")"
4. Otherwise, if
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
28 is used, then the result will be the value passed in to that method.

If an asynchronous generator happens to exit early by

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
29, the caller task being cancelled, or other exceptions, the generator’s async cleanup code will run and possibly raise exceptions or access context variables in an unexpected context–perhaps after the lifetime of tasks it depends, or during the event loop shutdown when the async-generator garbage collection hook is called. To prevent this, the caller must explicitly close the async generator by calling
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
30 method to finalize the generator and ultimately detach it from the event loop.

In an asynchronous generator function, yield expressions are allowed anywhere in a

generator_expression ::=  "(" expression comp_for ")"
6 construct. However, if an asynchronous generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), then a yield expression within a
generator_expression ::=  "(" expression comp_for ")"
6 construct could result in a failure to execute pending
generator_expression ::=  "(" expression comp_for ")"
8 clauses. In this case, it is the responsibility of the event loop or scheduler running the asynchronous generator to call the asynchronous generator-iterator’s
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
30 method and run the resulting coroutine object, thus allowing any pending
generator_expression ::=  "(" expression comp_for ")"
8 clauses to execute.

To take care of finalization upon event loop termination, an event loop should define a finalizer function which takes an asynchronous generator-iterator and presumably calls

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
30 and executes the coroutine. This finalizer may be registered by calling
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
37. When first iterated over, an asynchronous generator-iterator will store the registered finalizer to be called upon finalization. For a reference example of a finalizer method see the implementation of
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
38 in Lib/asyncio/base_events.py.

The expression

generator_expression ::=  "(" expression comp_for ")"
9 is a syntax error when used in an asynchronous generator function.

6.2.9.4. Asynchronous generator-iterator methods¶

This subsection describes the methods of an asynchronous generator iterator, which are used to control the execution of a generator function.

coroutine agen.__anext__()

Returns an awaitable which when run starts to execute the asynchronous generator or resumes it at the last executed yield expression. When an asynchronous generator function is resumed with an

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
26 method, the current yield expression always evaluates to
generator_expression ::=  "(" expression comp_for ")"
4 in the returned awaitable, which when run will continue to the next yield expression. The value of the
generator_expression ::=  "(" expression comp_for ")"
0 of the yield expression is the value of the
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
7 exception raised by the completing coroutine. If the asynchronous generator exits without yielding another value, the awaitable instead raises a
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
44 exception, signalling that the asynchronous iteration has completed.

This method is normally called implicitly by a

list_display ::=  "[" [starred_list | comprehension] "]"
3 loop.

coroutine agen.asend(value)

Returns an awaitable which when run resumes the execution of the asynchronous generator. As with the

generator_expression ::=  "(" expression comp_for ")"
5 method for a generator, this “sends” a value into the asynchronous generator function, and the value argument becomes the result of the current yield expression. The awaitable returned by the
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
28 method will return the next value yielded by the generator as the value of the raised
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
7, or raises
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
44 if the asynchronous generator exits without yielding another value. When
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
28 is called to start the asynchronous generator, it must be called with
generator_expression ::=  "(" expression comp_for ")"
4 as the argument, because there is no yield expression that could receive the value.

coroutine agen.athrow(type[, value[, traceback]])

Returns an awaitable that raises an exception of type

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
52 at the point where the asynchronous generator was paused, and returns the next value yielded by the generator function as the value of the raised
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
7 exception. If the asynchronous generator exits without yielding another value, a
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
44 exception is raised by the awaitable. If the generator function does not catch the passed-in exception, or raises a different exception, then when the awaitable is run that exception propagates to the caller of the awaitable.

coroutine agen.aclose()

Returns an awaitable that when run will throw a

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
17 into the asynchronous generator function at the point where it was paused. If the asynchronous generator function then exits gracefully, is already closed, or raises
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
17 (by not catching the exception), then the returned awaitable will raise a
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
7 exception. Any further awaitables returned by subsequent calls to the asynchronous generator will raise a
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
44 exception. If the asynchronous generator yields a value, a
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
19 is raised by the awaitable. If the asynchronous generator raises any other exception, it is propagated to the caller of the awaitable. If the asynchronous generator has already exited due to an exception or normal exit, then further calls to
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
30 will return an awaitable that does nothing.

6.3. Primaries¶

Primaries represent the most tightly bound operations of the language. Their syntax is:

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
2

6.3.1. Attribute references¶

An attribute reference is a primary followed by a period and a name:

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
3

The primary must evaluate to an object of a type that supports attribute references, which most objects do. This object is then asked to produce the attribute whose name is the identifier. This production can be customized by overriding the

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
61 method. If this attribute is not available, the exception
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
3 is raised. Otherwise, the type and value of the object produced is determined by the object. Multiple evaluations of the same attribute reference may yield different objects.

6.3.2. Subscriptions¶

The subscription of an instance of a container class will generally select an element from the container. The subscription of a generic class will generally return a GenericAlias object.

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
4

When an object is subscripted, the interpreter will evaluate the primary and the expression list.

The primary must evaluate to an object that supports subscription. An object may support subscription through defining one or both of

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
63 and
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
64. When the primary is subscripted, the evaluated result of the expression list will be passed to one of these methods. For more details on when
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
65 is called instead of
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
66, see __class_getitem__ versus __getitem__.

If the expression list contains at least one comma, it will evaluate to a

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
67 containing the items of the expression list. Otherwise, the expression list will evaluate to the value of the list’s sole member.

For built-in objects, there are two types of objects that support subscription via

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
63:

  1. Mappings. If the primary is a mapping, the expression list must evaluate to an object whose value is one of the keys of the mapping, and the subscription selects the value in the mapping that corresponds to that key. An example of a builtin mapping class is the

    atom      ::=  identifier | literal | enclosure
    enclosure ::=  parenth_form | list_display | dict_display | set_display
                   | generator_expression | yield_atom
    
    69 class.

  2. Sequences. If the primary is a sequence, the expression list must evaluate to an

    atom      ::=  identifier | literal | enclosure
    enclosure ::=  parenth_form | list_display | dict_display | set_display
                   | generator_expression | yield_atom
    
    70 or a
    atom      ::=  identifier | literal | enclosure
    enclosure ::=  parenth_form | list_display | dict_display | set_display
                   | generator_expression | yield_atom
    
    71 (as discussed in the following section). Examples of builtin sequence classes include the
    atom      ::=  identifier | literal | enclosure
    enclosure ::=  parenth_form | list_display | dict_display | set_display
                   | generator_expression | yield_atom
    
    72,
    atom      ::=  identifier | literal | enclosure
    enclosure ::=  parenth_form | list_display | dict_display | set_display
                   | generator_expression | yield_atom
    
    73 and
    atom      ::=  identifier | literal | enclosure
    enclosure ::=  parenth_form | list_display | dict_display | set_display
                   | generator_expression | yield_atom
    
    67 classes.

The formal syntax makes no special provision for negative indices in sequences. However, built-in sequences all provide a

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
63 method that interprets negative indices by adding the length of the sequence to the index so that, for example,
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
76 selects the last item of
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
77. The resulting value must be a nonnegative integer less than the number of items in the sequence, and the subscription selects the item whose index is that value (counting from zero). Since the support for negative indices and slicing occurs in the object’s
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
63 method, subclasses overriding this method will need to explicitly add that support.

A

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
79 is a special kind of sequence whose items are characters. A character is not a separate data type but a string of exactly one character.

6.3.3. Slicings¶

A slicing selects a range of items in a sequence object (e.g., a string, tuple or list). Slicings may be used as expressions or as targets in assignment or

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
80 statements. The syntax for a slicing:

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
5

There is ambiguity in the formal syntax here: anything that looks like an expression list also looks like a slice list, so any subscription can be interpreted as a slicing. Rather than further complicating the syntax, this is disambiguated by defining that in this case the interpretation as a subscription takes priority over the interpretation as a slicing (this is the case if the slice list contains no proper slice).

The semantics for a slicing are as follows. The primary is indexed (using the same

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
63 method as normal subscription) with a key that is constructed from the slice list, as follows. If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key. The conversion of a slice item that is an expression is that expression. The conversion of a proper slice is a slice object (see section The standard type hierarchy) whose
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
82,
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
83 and
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
84 attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting
generator_expression ::=  "(" expression comp_for ")"
4 for missing expressions.

6.3.4. Calls¶

A call calls a callable object (e.g., a function) with a possibly empty series of arguments:

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
6

An optional trailing comma may be present after the positional and keyword arguments but does not affect the semantics.

The primary must evaluate to a callable object (user-defined functions, built-in functions, methods of built-in objects, class objects, methods of class instances, and all objects having a

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
86 method are callable). All argument expressions are evaluated before the call is attempted. Please refer to section Function definitions for the syntax of formal parameter lists.

If keyword arguments are present, they are first converted to positional arguments, as follows. First, a list of unfilled slots is created for the formal parameters. If there are N positional arguments, they are placed in the first N slots. Next, for each keyword argument, the identifier is used to determine the corresponding slot (if the identifier is the same as the first formal parameter name, the first slot is used, and so on). If the slot is already filled, a

yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
4 exception is raised. Otherwise, the argument is placed in the slot, filling it (even if the expression is
generator_expression ::=  "(" expression comp_for ")"
4, it fills the slot). When all arguments have been processed, the slots that are still unfilled are filled with the corresponding default value from the function definition. (Default values are calculated, once, when the function is defined; thus, a mutable object such as a list or dictionary used as default value will be shared by all calls that don’t specify an argument value for the corresponding slot; this should usually be avoided.) If there are any unfilled slots for which no default value is specified, a
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
4 exception is raised. Otherwise, the list of filled slots is used as the argument list for the call.

CPython implementation detail: An implementation may provide built-in functions whose positional parameters do not have names, even if they are ‘named’ for the purpose of documentation, and which therefore cannot be supplied by keyword. In CPython, this is the case for functions implemented in C that use

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
90 to parse their arguments.

If there are more positional arguments than there are formal parameter slots, a

yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
4 exception is raised, unless a formal parameter using the syntax
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
92 is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments).

If any keyword argument does not correspond to a formal parameter name, a

yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
4 exception is raised, unless a formal parameter using the syntax
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
94 is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments.

If the syntax

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
95 appears in the function call,
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
96 must evaluate to an iterable. Elements from these iterables are treated as if they were additional positional arguments. For the call
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
97, if y evaluates to a sequence y1, …, yM, this is equivalent to a call with M+4 positional arguments x1, x2, y1, …, yM, x3, x4.

A consequence of this is that although the

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
95 syntax may appear after explicit keyword arguments, it is processed before the keyword arguments (and any
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
99 arguments – see below). So:

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
7

It is unusual for both keyword arguments and the

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
95 syntax to be used in the same call, so in practice this confusion does not often arise.

If the syntax

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
99 appears in the function call,
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
96 must evaluate to a mapping, the contents of which are treated as additional keyword arguments. If a parameter matching a key has already been given a value (by an explicit keyword argument, or from another unpacking), a
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
4 exception is raised.

When

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
99 is used, each key in this mapping must be a string. Each value from the mapping is assigned to the first formal parameter eligible for keyword assignment whose name is equal to the key. A key need not be a Python identifier (e.g.
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
05 is acceptable, although it will not match any formal parameter that could be declared). If there is no match to a formal parameter the key-value pair is collected by the
set_display ::=  "{" (starred_list | comprehension) "}"
5 parameter, if there is one, or if there is not, a
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
4 exception is raised.

Formal parameters using the syntax

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
92 or
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
94 cannot be used as positional argument slots or as keyword argument names.

Changed in version 3.5: Function calls accept any number of

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
10 and
set_display ::=  "{" (starred_list | comprehension) "}"
5 unpackings, positional arguments may follow iterable unpackings (
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
10), and keyword arguments may follow dictionary unpackings (
set_display ::=  "{" (starred_list | comprehension) "}"
5). Originally proposed by PEP 448.

A call always returns some value, possibly

generator_expression ::=  "(" expression comp_for ")"
4, unless it raises an exception. How this value is computed depends on the type of the callable object.

If it is—

a user-defined function:

The code block for the function is executed, passing it the argument list. The first thing the code block will do is bind the formal parameters to the arguments; this is described in section Function definitions. When the code block executes a

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
15 statement, this specifies the return value of the function call.

a built-in function or method:

The result is up to the interpreter; see Built-in Functions for the descriptions of built-in functions and methods.

a class object:

A new instance of that class is returned.

a class instance method:

The corresponding user-defined function is called, with an argument list that is one longer than the argument list of the call: the instance becomes the first argument.

a class instance:

The class must define a

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
86 method; the effect is then the same as if that method was called.

6.4. Await expression¶

Suspend the execution of coroutine on an awaitable object. Can only be used inside a coroutine function.

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
8

New in version 3.5.

6.5. The power operator¶

The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right. The syntax is:

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
9

Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands):

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
17 results in
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
18.

The power operator has the same semantics as the built-in

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
19 function, when called with two arguments: it yields its left argument raised to the power of its right argument. The numeric arguments are first converted to a common type, and the result is of that type.

For int operands, the result has the same type as the operands unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example,

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
20 returns
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
21, but
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
22 returns
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
23.

Raising

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
24 to a negative power results in a
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
25. Raising a negative number to a fractional power results in a
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
26 number. (In earlier versions it raised a
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
02.)

This operation can be customized using the special

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
28 method.

6.6. Unary arithmetic and bitwise operations¶

All unary arithmetic and bitwise operations have the same priority:

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
0

The unary

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
29 (minus) operator yields the negation of its numeric argument; the operation can be overridden with the
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
30 special method.

The unary

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
31 (plus) operator yields its numeric argument unchanged; the operation can be overridden with the
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
32 special method.

The unary

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
33 (invert) operator yields the bitwise inversion of its integer argument. The bitwise inversion of
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
77 is defined as
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
35. It only applies to integral numbers or to custom objects that override the
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
36 special method.

In all three cases, if the argument does not have the proper type, a

yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
4 exception is raised.

6.7. Binary arithmetic operations¶

The binary arithmetic operations have the conventional priority levels. Note that some of these operations also apply to certain non-numeric types. Apart from the power operator, there are only two levels, one for multiplicative operators and one for additive operators:

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
1

The

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
10 (multiplication) operator yields the product of its arguments. The arguments must either both be numbers, or one argument must be an integer and the other must be a sequence. In the former case, the numbers are converted to a common type and then multiplied together. In the latter case, sequence repetition is performed; a negative repetition factor yields an empty sequence.

This operation can be customized using the special

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
39 and
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
40 methods.

The

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
41 (at) operator is intended to be used for matrix multiplication. No builtin Python types implement this operator.

New in version 3.5.

The

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
42 (division) and
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
43 (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the ‘floor’ function applied to the result. Division by zero raises the
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
25 exception.

This operation can be customized using the special

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
45 and
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
46 methods.

The

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
47 (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
25 exception. The arguments may be floating point numbers, e.g.,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
49 equals
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
50 (since
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
51 equals
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
52.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand 1.

The floor division and modulo operators are connected by the following identity:

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
53. Floor division and modulo are also connected with the built-in function
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
54:
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
55. 2.

In addition to performing the modulo operation on numbers, the

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
47 operator is also overloaded by string objects to perform old-style string formatting (also known as interpolation). The syntax for string formatting is described in the Python Library Reference, section printf-style String Formatting.

The modulo operation can be customized using the special

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
57 method.

The floor division operator, the modulo operator, and the

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
54 function are not defined for complex numbers. Instead, convert to a floating point number using the
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
59 function if appropriate.

The

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
31 (addition) operator yields the sum of its arguments. The arguments must either both be numbers or both be sequences of the same type. In the former case, the numbers are converted to a common type and then added together. In the latter case, the sequences are concatenated.

This operation can be customized using the special

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
61 and
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
62 methods.

The

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
29 (subtraction) operator yields the difference of its arguments. The numeric arguments are first converted to a common type.

This operation can be customized using the special

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
64 method.

6.8. Shifting operations¶

The shifting operations have lower priority than the arithmetic operations:

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
2

These operators accept integers as arguments. They shift the first argument to the left or right by the number of bits given by the second argument.

This operation can be customized using the special

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
65 and
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
66 methods.

A right shift by n bits is defined as floor division by

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
67. A left shift by n bits is defined as multiplication with
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
67.

6.9. Binary bitwise operations¶

Each of the three bitwise operations has a different priority level:

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
3

The

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
69 operator yields the bitwise AND of its arguments, which must be integers or one of them must be a custom object overriding
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
70 or
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
71 special methods.

The

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
72 operator yields the bitwise XOR (exclusive OR) of its arguments, which must be integers or one of them must be a custom object overriding
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
73 or
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
74 special methods.

The

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
75 operator yields the bitwise (inclusive) OR of its arguments, which must be integers or one of them must be a custom object overriding
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
76 or
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
77 special methods.

6.10. Comparisons¶

Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
78 have the interpretation that is conventional in mathematics:

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
4

Comparisons yield boolean values:

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
79 or
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
80. Custom rich comparison methods may return non-boolean values. In this case Python will call
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
81 on such value in boolean contexts.

Comparisons can be chained arbitrarily, e.g.,

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
82 is equivalent to
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
83, except that
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
84 is evaluated only once (but in both cases
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
85 is not evaluated at all when
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
86 is found to be false).

Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
87 is equivalent to
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
88, except that each expression is evaluated at most once.

Note that

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
89 doesn’t imply any kind of comparison between a and c, so that, e.g.,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
90 is perfectly legal (though perhaps not pretty).

6.10.1. Value comparisons¶

The operators

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
91,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
92,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
93,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
94,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
95, and
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
96 compare the values of two objects. The objects do not need to have the same type.

Chapter Objects, values and types states that objects have a value (in addition to type and identity). The value of an object is a rather abstract notion in Python: For example, there is no canonical access method for an object’s value. Also, there is no requirement that the value of an object should be constructed in a particular way, e.g. comprised of all its data attributes. Comparison operators implement a particular notion of what the value of an object is. One can think of them as defining the value of an object indirectly, by means of their comparison implementation.

Because all types are (direct or indirect) subtypes of

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
97, they inherit the default comparison behavior from
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
97. Types can customize their comparison behavior by implementing rich comparison methods like
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
99, described in Basic customization.

The default behavior for equality comparison (

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
93 and
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
96) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e.
parenth_form ::=  "(" [starred_expression] ")"
02 implies
parenth_form ::=  "(" [starred_expression] ")"
03).

A default order comparison (

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
91,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
92,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
95, and
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
94) is not provided; an attempt raises
yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]
4. A motivation for this default behavior is the lack of a similar invariant as for equality.

The behavior of the default equality comparison, that instances with different identities are always unequal, may be in contrast to what types will need that have a sensible definition of object value and value-based equality. Such types will need to customize their comparison behavior, and in fact, a number of built-in types have done that.

The following list describes the comparison behavior of the most important built-in types.

User-defined classes that customize their comparison behavior should follow some consistency rules, if possible:

Python does not enforce these consistency rules. In fact, the not-a-number values are an example for not following these rules.

6.10.2. Membership test operations¶

The operators

parenth_form ::=  "(" [starred_expression] ")"
70 and
parenth_form ::=  "(" [starred_expression] ")"
71 test for membership.
parenth_form ::=  "(" [starred_expression] ")"
72 evaluates to
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
79 if x is a member of s, and
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
80 otherwise.
parenth_form ::=  "(" [starred_expression] ")"
75 returns the negation of
parenth_form ::=  "(" [starred_expression] ")"
72. All built-in sequences and set types support this as well as dictionary, for which
parenth_form ::=  "(" [starred_expression] ")"
70 tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression
parenth_form ::=  "(" [starred_expression] ")"
78 is equivalent to
parenth_form ::=  "(" [starred_expression] ")"
79.

For the string and bytes types,

parenth_form ::=  "(" [starred_expression] ")"
78 is
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
79 if and only if x is a substring of y. An equivalent test is
parenth_form ::=  "(" [starred_expression] ")"
82. Empty strings are always considered to be a substring of any other string, so
parenth_form ::=  "(" [starred_expression] ")"
83 will return
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
79.

For user-defined classes which define the

parenth_form ::=  "(" [starred_expression] ")"
85 method,
parenth_form ::=  "(" [starred_expression] ")"
78 returns
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
79 if
parenth_form ::=  "(" [starred_expression] ")"
88 returns a true value, and
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
80 otherwise.

For user-defined classes which do not define

parenth_form ::=  "(" [starred_expression] ")"
85 but do define
parenth_form ::=  "(" [starred_expression] ")"
91,
parenth_form ::=  "(" [starred_expression] ")"
78 is
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
79 if some value
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
85, for which the expression
parenth_form ::=  "(" [starred_expression] ")"
95 is true, is produced while iterating over
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
84. If an exception is raised during the iteration, it is as if
parenth_form ::=  "(" [starred_expression] ")"
70 raised that exception.

Lastly, the old-style iteration protocol is tried: if a class defines

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
63,
parenth_form ::=  "(" [starred_expression] ")"
78 is
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
79 if and only if there is a non-negative integer index i such that
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
01, and no lower integer index raises the
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
02 exception. (If any other exception is raised, it is as if
parenth_form ::=  "(" [starred_expression] ")"
70 raised that exception).

The operator

parenth_form ::=  "(" [starred_expression] ")"
71 is defined to have the inverse truth value of
parenth_form ::=  "(" [starred_expression] ")"
70.

6.10.3. Identity comparisons¶

The operators

parenth_form ::=  "(" [starred_expression] ")"
20 and
parenth_form ::=  "(" [starred_expression] ")"
21 test for an object’s identity:
parenth_form ::=  "(" [starred_expression] ")"
02 is true if and only if x and y are the same object. An Object’s identity is determined using the
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
09 function.
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
10 yields the inverse truth value. 4

6.11. Boolean operations¶

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
5

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false:

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
80,
generator_expression ::=  "(" expression comp_for ")"
4, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
13 method.

The operator

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
14 yields
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
79 if its argument is false,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
80 otherwise.

The expression

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
17 first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
18 first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

Note that neither

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
19 nor
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
20 restrict the value and type they return to
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
80 and
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
79, but rather return the last evaluated argument. This is sometimes useful, e.g., if
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
23 is a string that should be replaced by a default value if it is empty, the expression
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
24 yields the desired value. Because
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
14 has to create a new value, it returns a boolean value regardless of the type of its argument (for example,
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
26 produces
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
80 rather than
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
28.)

6.12. Assignment expressions¶

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
6

An assignment expression (sometimes also called a “named expression” or “walrus”) assigns an

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
96 to an
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
30, while also returning the value of the
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
96.

One common use case is when handling matched regular expressions:

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
7

Or, when processing a file stream in chunks:

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
8

Assignment expressions must be surrounded by parentheses when used as sub-expressions in slicing, conditional, lambda, keyword-argument, and comprehension-if expressions and in

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
32 and
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
33 statements. In all other places where they can be used, parentheses are not required, including in
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
2 and
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
35 statements.

New in version 3.8: See PEP 572 for more details about assignment expressions.

6.13. Conditional expressions¶

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
9

Conditional expressions (sometimes called a “ternary operator”) have the lowest priority of all Python operations.

The expression

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
36 first evaluates the condition, C rather than x. If C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

See PEP 308 for more details about conditional expressions.

6.14. Lambdas¶

parenth_form ::=  "(" [starred_expression] ")"
0

Lambda expressions (sometimes called lambda forms) are used to create anonymous functions. The expression

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
37 yields a function object. The unnamed object behaves like a function object defined with:

parenth_form ::=  "(" [starred_expression] ")"
1

See section Function definitions for the syntax of parameter lists. Note that functions created with lambda expressions cannot contain statements or annotations.

6.15. Expression lists¶

parenth_form ::=  "(" [starred_expression] ")"
2

Except when part of a list or set display, an expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.

An asterisk

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
10 denotes iterable unpacking. Its operand must be an iterable. The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.

New in version 3.5: Iterable unpacking in expression lists, originally proposed by PEP 448.

The trailing comma is required only to create a single tuple (a.k.a. a singleton); it is optional in all other cases. A single expression without a trailing comma doesn’t create a tuple, but rather yields the value of that expression. (To create an empty tuple, use an empty pair of parentheses:

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
39.)

6.16. Evaluation order¶

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

In the following lines, expressions will be evaluated in the arithmetic order of their suffixes:

parenth_form ::=  "(" [starred_expression] ")"
3

6.17. Operator precedence¶

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).

Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.

Operator

Description

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
40,

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
41,
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
42,
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
43

Binding or parenthesized expression, list display, dictionary display, set display

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
44,
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
45,
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
46,
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
47

Subscription, slicing, call, attribute reference

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
48

Await expression

set_display ::=  "{" (starred_list | comprehension) "}"
5

Exponentiation 5

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
50,
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
51,
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
52

Positive, negative, bitwise NOT

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
10,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
41,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
42,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
43,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
47

Multiplication, matrix multiplication, division, floor division, remainder 6

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
31,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
29

Addition and subtraction

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
60,
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
61

Shifts

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
69

Bitwise AND

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
72

Bitwise XOR

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
75

Bitwise OR

parenth_form ::=  "(" [starred_expression] ")"
70,
parenth_form ::=  "(" [starred_expression] ")"
71,
parenth_form ::=  "(" [starred_expression] ")"
20,
parenth_form ::=  "(" [starred_expression] ")"
21,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
91,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
95,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
92,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
94,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
96,
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
93

Comparisons, including membership tests and identity tests

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
75

Boolean NOT

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
19

Boolean AND

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
20

Boolean OR

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
2 –
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
79

Conditional expression

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
80

Lambda expression

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
81

Assignment expression

Footnotes

1

While

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
82 is true mathematically, for floats it may not be true numerically due to roundoff. For example, and assuming a platform on which a Python float is an IEEE 754 double-precision number, in order that
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
83 have the same sign as
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
84, the computed result is
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
85, which is numerically exactly equal to
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
84. The function
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
87 returns a result whose sign matches the sign of the first argument instead, and so returns
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
88 in this case. Which approach is more appropriate depends on the application.

2

If x is very close to an exact integer multiple of y, it’s possible for

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
89 to be one larger than
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
90 due to rounding. In such cases, Python returns the latter result, in order to preserve that
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
91 be very close to
atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom
77.

3

The Unicode standard distinguishes between code points (e.g. U+0041) and abstract characters (e.g. “LATIN CAPITAL LETTER A”). While most abstract characters in Unicode are only represented using one code point, there is a number of abstract characters that can in addition be represented using a sequence of more than one code point. For example, the abstract character “LATIN CAPITAL LETTER C WITH CEDILLA” can be represented as a single precomposed character at code position U+00C7, or as a sequence of a base character at code position U+0043 (LATIN CAPITAL LETTER C), followed by a combining character at code position U+0327 (COMBINING CEDILLA).

The comparison operators on strings compare at the level of Unicode code points. This may be counter-intuitive to humans. For example,

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
93 is
literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber
80, even though both strings represent the same abstract character “LATIN CAPITAL LETTER C WITH CEDILLA”.

To compare strings at the level of abstract characters (that is, in a way intuitive to humans), use

comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
95.

4

Due to automatic garbage-collection, free lists, and the dynamic nature of descriptors, you may notice seemingly unusual behaviour in certain uses of the

parenth_form ::=  "(" [starred_expression] ")"
20 operator, like those involving comparisons between instance methods, or constants. Check their documentation for more info.

5

The power operator

set_display ::=  "{" (starred_list | comprehension) "}"
5 binds less tightly than an arithmetic or bitwise unary operator on its right, that is,
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
98 is
comprehension ::=  assignment_expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" or_test [comp_iter]
99.