GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||
GeezerVison is showing docs.python.org — 6. Expressions 6. Expressions¶This chapter explains the meaning of the elements of expressions in Python. Syntax Notes: In this and the following chapters, grammar 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 6.1. Arithmetic conversions¶When a description of an arithmetic operator below uses the phrase “the numeric arguments are converted to a common real type”, this means that the operator implementation for built-in numeric types works as described in the Numeric Types section of the standard library documentation. Some additional rules apply for certain operators and non-numeric operands
(for example, a string as a left argument to the 6.2. Atoms¶Atoms are the most basic elements of expressions. The simplest atoms are builtin constants, names and literals. More complex atoms are enclosed in paired delimiters:
Formally, the syntax for atoms is: atom: | 6.2.1. Built-in constants¶The keywords Evaluation of these atoms yields the corresponding value. Note Several more built-in constants are available as global variables, but only the ones mentioned here are keywords. In particular, these names cannot be reassigned or used as attributes: >>> False = 123 File "<input>", line 1 False = 123 ^^^^^ SyntaxError: cannot assign to False Formally, the syntax for built-in constants is: builtin_constant: 'True' | 'False' | 'None' | '...' 6.2.2. Identifiers (Names)¶An identifier occurring as an atom is a name. See section Names (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 6.2.2.1. 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. See also The class specifications. More precisely, private names are transformed to a longer form before code is generated for them. If the transformed name is longer than 255 characters, implementation-defined truncation may happen. The transformation is independent of the syntactical context in which the identifier is used but only the following private identifiers are mangled:
The transformation rule is defined as follows:
6.2.3. Literals¶A literal is a textual representation of a value. Python supports numeric, string and bytes literals. Format strings and template strings are treated as string literals. Numeric literals consist of a single String and bytes literals may consist of several tokens. See section String literal concatenation for details. Note that negative and complex numbers, like Evaluation of a literal yields an object of the given type
( The formal grammar for literals is: literal: 6.2.3.1. Literals and object identity¶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. CPython implementation detail For example, in CPython, small integers with the same value evaluate to the same object: >>> x = 7 >>> y = 7 >>> x is y True However, large integers evaluate to different objects: >>> x = 123456789 >>> y = 123456789 >>> x is y False This behavior may change in future versions of CPython. In particular, the boundary between “small” and “large” integers has already changed in the past. CPython will emit a >>> x = 7 >>> x is 7 <input>:1: SyntaxWarning: "is" with 'int' literal. Did you mean "=="? True See When can I rely on identity tests with the is operator? for more information. Template strings are immutable but may reference mutable
objects as CPython implementation detail: Currently, each evaluation of a template string results in a different object. 6.2.3.2. String literal concatenation¶Multiple adjacent string or bytes literals, possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation: >>> "hello" 'world' "helloworld" This feature is defined at the syntactical level, so it only works with literals. To concatenate string expressions at run time, the ‘+’ operator may be used: >>> greeting = "Hello" >>> space = " " >>> name = "Blaise" >>> print(greeting + space + name) # not: print(greeting space name) Hello Blaise Literal concatenation can freely mix raw strings, triple-quoted strings, and formatted string literals. For example: >>> "Hello" r', ' f"{name}!" "Hello, Blaise!" This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings. For example: re.compile("[A-Za-z_]" # letter or underscore "[A-Za-z0-9_]*" # letter, digit or underscore ) However, bytes literals may only be combined with other byte literals; not with string literals of any kind. Also, template string literals may only be combined with other template string literals: >>> t"Hello" t"{name}!" Template(strings=('Hello', '!'), interpolations=(...)) Formally: strings: ( 6.2.4. Parenthesized groups¶A parenthesized group is an expression enclosed in parentheses. The group evaluates to the same value as the expression inside. Groups are used to override or clarify operator precedence, in the same way as in math notation. For example: >>> 3 << 2 | 4 12 >>> 3 << (2 | 4) # Override precedence of the | (bitwise OR) 192 >>> (3 << 2) | 4 # Same as without parentheses (but more clear) 12 Note that not everything in parentheses is a group. Specifically, a parenthesized group must include exactly one expression, and cannot end with a comma. See tuple displays and generator expressions for other parenthesized forms. Formally, the syntax for groups is: group: '('
6.2.5. Container displays¶For constructing builtin containers (lists, sets, tuples or dictionaries), Python provides special syntax called displays. There are subtle differences between the four kinds of displays, detailed in the following sections. All displays, however, consist of comma-separated items enclosed in paired delimiters. For example, a list display is a series of expressions enclosed in square brackets: >>> ["one", "two", "three"] ['one', 'two', 'three'] >>> [1 + 2, 2 + 3] [3, 5] In list, tuple and dictionary (but not set) displays, the series may be empty: >>> [] # empty list [] >>> () # empty tuple () >>> {} # empty dictionary {} If the series is not empty, the items may be followed by an additional comma, which has no effect: >>> ["one", "two", "three",] # note comma after "three" ['one', 'two', 'three'] Note The trailing comma is often used for displays that span multiple lines (using implicit line joining), so when a future programmer adds a new entry at the end, they do not need to modify an existing line: >>> [ ... 'one', ... 'two', ... 'three', ... ] ['one', 'two', 'three'] At runtime, when a display is evaluated, the listed items are evaluated from left to right and placed into a new container of the appropriate type. For tuple, list and set (but not dict) displays, any item in the display may
be prefixed with an asterisk ( >>> numbers = (1, 2) >>> [*numbers, 'word', *numbers] [1, 2, 'word', 1, 2] Dictionary displays use a similar mechanism called
dictionary unpacking, denoted with a double
asterisk ( A more advanced form of displays are comprehensions, where items are computed via a set of looping and filtering instructions. See the Comprehensions section for details. Added in version 3.5: Iterable and dictionary unpacking in displays, originally proposed by PEP 448. 6.2.5.1. List displays¶A list display is a possibly empty series of expressions enclosed in square brackets. For example: >>> ["one", "two", "three"] ['one', 'two', 'three'] >>> ["one"] # One-element list ['one'] >>> [] # empty list [] See Container displays for general information on displays. The formal grammar for list displays is: list: '[' [
6.2.5.2. Set displays¶A set display is a non-empty series of expressions enclosed in curly braces. For example: >>> {"one", "two", "three"} {'one', 'three', 'two'} >>> {"one"} # One-element set {'one'} See Container displays for general information on displays. There is no special syntax for the empty set.
The The formal grammar for set displays is: set: '{'
6.2.5.3. Tuple displays¶A tuple display is a series of expressions enclosed in parentheses. For example: >>> (1, 2) (1, 2) >>> () # an empty tuple () See Container displays for general information on displays. To avoid ambiguity, if a tuple display has exactly one element, it requires a trailing comma. Without it, you get a parenthesized group: >>> ('single',) # single-element tuple ('single',) >>> ('single') # no comma: single string 'single' To put it in other words, a tuple display is a parenthesized list of either:
Since tuples are immutable, object identity rules for literals also apply to tuples: at runtime, two occurrences of tuples with the same values may or may not yield the same object. Note Python’s syntax also includes expression lists, where a comma-separated list of expressions is not enclosed in parentheses but evaluates to tuple. In other words, when it comes to tuple syntax, the comma is more important that the use of parentheses. Only the empty tuple is spelled without a comma. The formal grammar for tuple displays is: tuple: | '(' 6.2.5.4. Dictionary displays¶A dictionary display is a possibly empty series of dict items enclosed in curly braces. Each dict item is a colon-separated pair of expressions: the key and its associated value. For example: >>> {1: 'one', 2: 'two'} {1: 'one', 2: 'two'} At runtime, when a dictionary comprehension is evaluated, the expressions are evaluated from left to right. Each key object is used as a key into the dictionary to store the corresponding value. This means that you can specify the same key multiple times in the comprehension, and the final dictionary’s value for a given key will be the last one given. For example: >>> { ... 1: 'this will be overridden', ... 2: 'two', ... 1: 'also overridden', ... 1: 'one', ... } {1: 'one', 2: 'two'} Instead of a key-value pair, a dict item may be an expression prefixed by
a double asterisk >>> defaults = {'color': 'blue', 'count': 8} >>> overrides = {'color': 'yellow'} >>> {**defaults, **overrides} {'color': 'yellow', 'count': 8} Added in version 3.5: Unpacking into dictionary displays, originally proposed by PEP 448. The formal grammar for dict displays is: dict: '{' [ 6.2.6. Comprehensions¶List, set and dictionary comprehensions are a form of container displays where items are computed via a set of looping and filtering instructions rather than listed explicitly. In its simplest form, a comprehension consists of a single expression
followed by a For example, a list of the first ten squares is: >>> [x**2 for x in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] At run time, a list comprehension creates a new list.
The expression after def make_list_of_squares(iterable): result = [] for x in iterable: result.append(x**2) return result make_list_of_squares(range(10)) Set comprehensions work similarly. For example, here is a set of lowercase letters: >>> {x.lower() for x in ['a', 'A', 'b', 'C']} {'c', 'a', 'b'} At run time, this corresponds roughly to calling this function: def make_lowercase_set(iterable): result = set() for x in iterable: result.add(x.lower()) return result make_lowercase_set(['a', 'A', 'b', 'C']) Dictionary comprehensions start with a colon-separated key-value pair instead of an expression. For example: >>> {func.__name__: func for func in [print, hex, any]} {'print': <built-in function print>, 'hex': <built-in function hex>, 'any': <built-in function any>} At run time, this corresponds roughly to: def make_dict_mapping_names_to_functions(iterable): result = {} for func in iterable: result[func.__name__] = func return result make_dict_mapping_names_to_functions([print, hex, any]) As in other kinds of dictionary displays, the same key may be specified multiple times. Earlier values are overwritten by ones that are evaluated later. There are no tuple comprehensions. A similar syntax is instead used for generator expressions, from which you can construct a tuple like this: >>> tuple(x**2 for x in range(10)) (0, 1, 4, 9, 16, 25, 36, 49, 64, 81) 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.6.1. Filtering in comprehensions¶The For example, a list of names from the >>> [name for name in vars(math) if name.startswith('f')] ['fabs', 'factorial', 'floor', 'fma', 'fmod', 'frexp', 'fsum'] At run time, the expression after def get_math_f_names(iterable): result = [] for name in iterable: if name.startswith('f'): result.append(name) return result get_math_f_names(vars(math)) Filtering is a special case of more complex comprehensions. See the next section for a more formal description. 6.2.6.2. Complex comprehensions¶Generally, a comprehension’s initial >>> import array >>> import math >>> [ ... name ... for module in [array, math] ... for name in vars(module) ... if name.startswith('a') ... ] ['array', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh'] At run time, this roughly corresponds to defining and calling: def get_a_names(iterable): result = [] for module in iterable: for name in vars(module): if name.startswith('a'): result.append(name) return result get_a_names([array, math]) The elements of the new container are those that would be produced by
considering each of the Aside from the iterable expression in the leftmost >>> x = 'old value' >>> [x**2 for x in range(10)] # this `x` is local to the comprehension >>> x 'old value' The iterable expression in the leftmost Subsequent To ensure the comprehension always results in a container of the appropriate
type, Assignment expressions are not allowed
inside comprehension iterable expressions (that is, the expressions after
the Changed in version 3.8: 6.2.6.3. Unpacking in comprehensions¶If the expression of a list or set comprehension is starred, the result will be unpacked to produce zero or more elements. This is often used for “flattening” lists, for example: >>> students = ['Petr', 'Blaise', 'Jarka'] >>> teachers = ['Salim', 'Bartosz'] >>> lists_of_people = [students, teachers] >>> [*people for people in lists_of_people] ['Petr', 'Blaise', 'Jarka', 'Salim', 'Bartosz'] At run time, this comprehension roughly corresponds to: def flatten_names(lists_of_people): result = [] for people in lists_of_people: result.extend(people) return result In dict comprehensions, a double-starred expression will be evaluated and then unpacked using dictionary unpacking, inserting zero or more key/value pairs into the new dictionary. As in other kinds of dictionary displays, if the same key is specified multiple times, the associated value in the resulting dictionary will be the last one specified. For example: >>> system_defaults = {'color': 'blue', 'count': 8} >>> user_defaults = {'color': 'yellow'} >>> overrides = {'count': 5} >>> configuration_sets = [system_defaults, user_defaults, overrides] >>> {**d for d in configuration_sets} {'color': 'yellow', 'count': 5} Added in version 3.15: Unpacking in comprehensions using the 6.2.6.4. Asynchronous comprehensions¶In an If a comprehension contains Added in version 3.6: Asynchronous comprehensions were introduced in PEP 530. Changed in version 3.11: Asynchronous comprehensions are now allowed inside comprehensions in asynchronous functions. Outer comprehensions implicitly become asynchronous. 6.2.6.5. Formal grammar for comprehensions¶The formal grammar for comprehensions is: listcomp: '[' 6.2.7. Generator expressions¶The syntax for generator expressions is the same as for list comprehensions, except that they are enclosed in parentheses instead of brackets. For example: >>> iterator = (x ** 2 for x in range(10)) >>> iterator <generator object <genexpr> at ...> At runtime, a generator expression evaluates to a generator iterator which yields the same values as the corresponding list comprehension: >>> list(iterator) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] Thus, the example above is roughly equivalent to defining and calling the following generator function: def make_generator_of_squares(iterator): for x in iterator: yield x ** 2 make_generator_of_squares(iter(range(10))) The enclosing parentheses can be omitted in calls when the generator expression is the only positional argument and there are no keyword arguments. See the Calls section for details. For example: # The parentheses after `sum` are part of the call syntax: >>> sum(x ** 2 for x in range(10)) 285 # The generator needs its own parentheses if it's not the only argument: >>> sum((x ** 2 for x in range(10)), start=1000) 1285 The iterable expression in the leftmost >>> (x ** 2 for x in nonexistent_iterable) Traceback (most recent call last): ... NameError: name 'nonexistent_iterable' is not defined After the expression is evaluated, an iterator is created
from the result, as if >>> (x ** 2 for x in None) Traceback (most recent call last): ... TypeError: 'NoneType' object is not iterable All other expressions are evaluated lazily, in the same fashion as normal generators (that is, when the iterator is asked to yield a value): >>> iterator = (nonexistent_value for x in range(10)) >>> iterator <generator object <genexpr> at ...> >>> list(iterator) Traceback (most recent call last): ... NameError: name 'nonexistent_value' is not defined >>> iterator = (x * y for x in range(10) for y in nonexistent_iterable) >>> iterator <generator object <genexpr> at ...> >>> list(iterator) Traceback (most recent call last): ... NameError: name 'nonexistent_iterable' is not defined To avoid interfering with the expected operation of the generator expression
itself, If a generator expression contains either The formal grammar for generator expressions is: generator_expression: "("
Added 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 Changed in version 3.8: 6.2.8. Yield expressions¶yield_atom: "(" 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 def gen(): # defines a generator function yield 123 async def agen(): # defines an asynchronous generator function yield 123 Due to their side effects on the containing scope, 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 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 When When the underlying iterator is complete, the Changed in version 3.3: Added The parentheses may be omitted when the yield expression is the sole expression on the right hand side of an assignment statement. See also
6.2.8.1. Examples¶Here is a simple example that demonstrates the behavior of generators and generator functions: >>> def echo(value=None): ... print("Execution starts when 'next()' is called for the first time.") ... try: ... while True: ... try: ... value = (yield value) ... except Exception as e: ... value = e ... finally: ... print("Don't forget to clean up when 'close()' is called.") ... >>> generator = echo(1) >>> print(next(generator)) Execution starts when 'next()' is called for the first time. 1 >>> print(next(generator)) None >>> print(generator.send(2)) 2 >>> generator.throw(TypeError, "spam") TypeError('spam',) >>> generator.close() Don't forget to clean up when 'close()' is called. For examples using 6.2.8.2. Asynchronous generator functions¶The presence of a yield expression in a function or method defined using
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
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 If an asynchronous generator happens to exit early by In an asynchronous generator function, yield expressions are allowed anywhere
in a To handle finalization when an asynchronous generator is about to be garbage
collected, an event loop should define a finalizer function which takes an
asynchronous generator-iterator and schedules the awaitable returned by
The expression 6.3. Primaries¶Primaries represent the most tightly bound operations of the language. Their syntax is: primary: 6.3.1. Attribute references¶An attribute reference is a primary followed by a period and a name: attributeref: 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. The type and value produced is determined by the object. Multiple evaluations of the same attribute reference may yield different objects. This production can be customized by overriding the
If an 6.3.2. Subscriptions and slicings¶The subscription syntax is usually used for selecting an element from a
container – for example, to get a value from
a >>> digits_by_name = {'one': 1, 'two': 2} >>> digits_by_name['two'] # Subscripting a dictionary using the key 'two' 2 In the subscription syntax, the object being subscribed – a primary – is followed by a subscript in square brackets. In the simplest case, the subscript is a single expression. Depending on the type of the object being subscribed, the subscript is sometimes called a key (for mappings), index (for sequences), or type argument (for generic types). Syntactically, these are all equivalent: >>> colors = ['red', 'blue', 'green', 'black'] >>> colors[3] # Subscripting a list using the index 3 'black' >>> list[str] # Parameterizing the list type using the type argument str list[str] At runtime, the interpreter will evaluate the primary and
the subscript, and call the primary’s To show how subscription works, we can define a custom object that
implements >>> class SubscriptionDemo: ... def __getitem__(self, key): ... print(f'subscripted with: {key!r}') ... >>> demo = SubscriptionDemo() >>> demo[1] subscripted with: 1 >>> demo['a' * 3] subscripted with: 'aaa' See Subscriptions may also be used as targets in assignment or
deletion statements.
In these cases, the interpreter will call the subscripted object’s
>>> colors = ['red', 'blue', 'green', 'black'] >>> colors[3] = 'white' # Setting item at index >>> colors ['red', 'blue', 'green', 'white'] >>> del colors[3] # Deleting item at index 3 >>> colors ['red', 'blue', 'green'] All advanced forms of subscript documented in the following sections are also usable for assignment and deletion. 6.3.2.1. Slicings¶A more advanced form of subscription, slicing, is commonly used to extract a portion of a sequence. In this form, the subscript is a slice: up to three expressions separated by colons. Any of the expressions may be omitted, but a slice must contain at least one colon: >>> number_names = ['zero', 'one', 'two', 'three', 'four', 'five'] >>> number_names[1:3] ['one', 'two'] >>> number_names[1:] ['one', 'two', 'three', 'four', 'five'] >>> number_names[:3] ['zero', 'one', 'two'] >>> number_names[:] ['zero', 'one', 'two', 'three', 'four', 'five'] >>> number_names[::2] ['zero', 'two', 'four'] >>> number_names[:-3] ['zero', 'one', 'two'] >>> del number_names[4:] >>> number_names ['zero', 'one', 'two', 'three'] When a slice is evaluated, the interpreter constructs a # continuing with the SubscriptionDemo instance defined above: >>> demo[2:3] subscripted with: slice(2, 3, None) >>> demo[::'spam'] subscripted with: slice(None, None, 'spam') 6.3.2.2. Comma-separated subscripts¶The subscript can also be given as two or more comma-separated expressions or slices: # continuing with the SubscriptionDemo instance defined above: >>> demo[1, 2, 3] subscripted with: (1, 2, 3) >>> demo[1:2, 3] subscripted with: (slice(1, 2, None), 3) This form is commonly used with numerical libraries for slicing
multi-dimensional data.
In this case, the interpreter constructs a The subscript may also be given as a single expression or slice followed by a comma, to specify a one-element tuple: >>> demo['spam',] subscripted with: ('spam',) 6.3.2.3. “Starred” subscriptions¶Added in version 3.11: Expressions in tuple_slices may be starred. See PEP 646. The subscript can also contain a starred expression.
In this case, the interpreter unpacks the result into a tuple, and passes
this tuple to # continuing with the SubscriptionDemo instance defined above: >>> demo[*range(10)] subscripted with: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) Starred expressions may be combined with comma-separated expressions and slices: >>> demo['a', 'b', *range(3), 'c'] subscripted with: ('a', 'b', 0, 1, 2, 'c') 6.3.2.4. Formal subscription grammar¶subscription: Recall that the 6.3.3. Calls¶A call calls a callable object (e.g., a function) with a possibly empty series of arguments: call: 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 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 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 If there are more positional arguments than there are formal parameter slots, a
If any keyword argument does not correspond to a formal parameter name, a
If the syntax A consequence of this is that although the >>> def f(a, b): ... print(a, b) ... >>> f(b=1, *(2,)) 2 1 >>> f(a=1, *(2,)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: f() got multiple values for keyword argument 'a' >>> f(1, *(2,)) 1 2 It is unusual for both keyword arguments and the If the syntax When Formal parameters using the syntax Changed in version 3.5: Function calls accept any number of A call always returns some value, possibly If it is—
6.4. Await expression¶Suspend the execution of coroutine on an awaitable object. Can only be used inside a coroutine function. await_expr: "await"
Added 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: power: ( 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): The power operator has the same semantics as the built-in 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, Raising This operation can be customized using the special 6.6. Unary arithmetic and bitwise operations¶All unary arithmetic and bitwise operations have the same priority: u_expr: The unary The unary The unary In all three cases, if the argument does not have the proper type, a
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: m_expr: The This operation can be customized using the special Changed in version 3.14: If only one operand is a complex number, the other operand is converted to a floating-point number. The This operation can be customized using the special Added in version 3.5. The The division operation can be customized using the special The The floor division and modulo operators are connected by the following
identity: In addition to performing the modulo operation on numbers, the The modulo operation can be customized using the special The floor division operator, the modulo operator, and the The This operation can be customized using the special Changed in version 3.14: If only one operand is a complex number, the other operand is converted to a floating-point number. The This operation can be customized using the special Changed in version 3.14: If only one operand is a complex number, the other operand is converted to a floating-point number. 6.8. Shifting operations¶The shifting operations have lower priority than the arithmetic operations: shift_expr: 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. The left shift operation can be customized using the special A right shift by n bits is defined as floor division by 6.9. Binary bitwise operations¶Each of the three bitwise operations has a different priority level: and_expr: The The The 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 comparison: Comparisons yield boolean values: Comparisons can be chained arbitrarily, e.g., Formally, if a, b, c, …, y, z are expressions and op1, op2, …,
opN are comparison operators, then Note that 6.10.1. Value comparisons¶The operators 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 The default behavior for equality comparison ( A default order comparison ( 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 For the string and bytes types, For user-defined classes which define the For user-defined classes which do not define Lastly, the old-style iteration protocol is tried: if a class defines
The operator 6.10.3. Identity comparisons¶The operators 6.11. Boolean operations¶or_test: In the context of Boolean operations, and also when expressions are used by
control flow statements, the following values are interpreted as false:
The operator The expression The expression Note that neither 6.12. Assignment expressions¶assignment_expression: [ An assignment expression (sometimes also called a “named expression” or
“walrus”) assigns an One common use case is when handling matched regular expressions: if matching := pattern.search(data): do_something(matching) Or, when processing a file stream in chunks: while chunk := file.read(9000): process(chunk) Assignment expressions must be surrounded by parentheses when
used as expression statements and when used as sub-expressions in
slicing, conditional, lambda,
keyword-argument, and comprehension-if expressions and
in Added in version 3.8: See PEP 572 for more details about assignment expressions. 6.13. Conditional expressions¶conditional_expression: A conditional expression (sometimes called a “ternary operator”) is an alternative to the if-else statement. As it is an expression, it returns a value and can appear as a sub-expression. The expression See PEP 308 for more details about conditional expressions. 6.14. Lambdas¶lambda_expr: "lambda" [ Lambda expressions (sometimes called lambda forms) are used to create anonymous
functions. The expression def <lambda>(parameters):
return expression
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¶starred_expression: "*" 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. A trailing comma is required only to create a one-item tuple,
such as 6.15.1. Iterable unpacking¶In an expression list or tuple, list or set display, any expression
may be prefixed with an asterisk ( At runtime, the asterisk-prefixed expression must evaluate to 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. Added in version 3.5: Iterable unpacking in expression lists, originally proposed by PEP 448. Added in version 3.11: Any item in an expression list may be starred. See PEP 646. 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: expr1, expr2, expr3, expr4 (expr1, expr2, expr3, expr4) {expr1: expr2, expr3: expr4} expr1 + expr2 * (expr3 - expr4) expr1(expr2, expr3, *expr4, **expr5) expr3, expr4 = expr1, expr2 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.
Footnotes
© Copyright 2001 Python Software Foundation.
This page is licensed under the Python Software Foundation License Version 2. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License. See History and License for more information. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Nov 12, 2026 (14:21 UTC). Found a bug? Created using Sphinx 9.1.1. | ||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |