summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/reference%2Fexpressions.html
blob: f0de06aff30b33af1e8d329f97e38a69af3b3bb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
 <span id="id1"></span><h1> Expressions</h1> <p id="index-0">This chapter explains the meaning of the elements of expressions in Python.</p> <p><strong>Syntax Notes:</strong> 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</p> <pre>
<strong id="grammar-token-python-grammar-name"><span id="grammar-token-name"></span>name</strong> ::=  <code>othername</code>
</pre> <p>and no semantics are given, the semantics of this form of <code>name</code> are the same as for <code>othername</code>.</p> <section id="arithmetic-conversions"> <span id="conversions"></span><h2>
<span class="section-number">6.1. </span>Arithmetic conversions</h2> <p id="index-1">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:</p> <ul class="simple"> <li>If either argument is a complex number, the other is converted to complex;</li> <li>otherwise, if either argument is a floating point number, the other is converted to floating point;</li> <li>otherwise, both must be integers and no conversion is necessary.</li> </ul> <p>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.</p> </section> <section id="atoms"> <span id="id2"></span><h2>
<span class="section-number">6.2. </span>Atoms</h2> <p id="index-2">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:</p> <pre>
<strong id="grammar-token-python-grammar-atom"><span id="grammar-token-atom"></span>atom     </strong> ::=  <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-identifier">identifier</a> | <a class="reference internal" href="#grammar-token-python-grammar-literal">literal</a> | <a class="reference internal" href="#grammar-token-python-grammar-enclosure">enclosure</a>
<strong id="grammar-token-python-grammar-enclosure"><span id="grammar-token-enclosure"></span>enclosure</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-parenth_form">parenth_form</a> | <a class="reference internal" href="#grammar-token-python-grammar-list_display">list_display</a> | <a class="reference internal" href="#grammar-token-python-grammar-dict_display">dict_display</a> | <a class="reference internal" href="#grammar-token-python-grammar-set_display">set_display</a>
               | <a class="reference internal" href="#grammar-token-python-grammar-generator_expression">generator_expression</a> | <a class="reference internal" href="#grammar-token-python-grammar-yield_atom">yield_atom</a>
</pre> <section id="atom-identifiers"> <span id="identifiers-names"></span><h3>
<span class="section-number">6.2.1. </span>Identifiers (Names)</h3> <p id="index-3">An identifier occurring as an atom is a name. See section <a class="reference internal" href="lexical_analysis#identifiers"><span class="std std-ref">Identifiers and keywords</span></a> for lexical definition and section <a class="reference internal" href="executionmodel#naming"><span class="std std-ref">Naming and binding</span></a> for documentation of naming and binding.</p> <p id="index-4">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 <a class="reference internal" href="../library/exceptions#NameError" title="NameError"><code>NameError</code></a> exception.</p> <span class="target" id="private-name-mangling"></span><p id="index-5"><strong>Private name mangling:</strong> 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 <em class="dfn">private name</em> 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 <code>__spam</code> occurring in a class named <code>Ham</code> will be transformed to <code>_Ham__spam</code>. 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.</p> </section> <section id="literals"> <span id="atom-literals"></span><h3>
<span class="section-number">6.2.2. </span>Literals</h3> <p id="index-6">Python supports string and bytes literals and various numeric literals:</p> <pre>
<strong id="grammar-token-python-grammar-literal"><span id="grammar-token-literal"></span>literal</strong> ::=  <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-stringliteral">stringliteral</a> | <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-bytesliteral">bytesliteral</a>
             | <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-integer">integer</a> | <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-floatnumber">floatnumber</a> | <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-imagnumber">imagnumber</a>
</pre> <p>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 <a class="reference internal" href="lexical_analysis#literals"><span class="std std-ref">Literals</span></a> for details.</p> <p id="index-7">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.</p> </section> <section id="parenthesized-forms"> <span id="parenthesized"></span><h3>
<span class="section-number">6.2.3. </span>Parenthesized forms</h3> <p id="index-8">A parenthesized form is an optional expression list enclosed in parentheses:</p> <pre>
<strong id="grammar-token-python-grammar-parenth_form"><span id="grammar-token-parenth-form"></span>parenth_form</strong> ::=  "(" [<a class="reference internal" href="#grammar-token-python-grammar-starred_expression">starred_expression</a>] ")"
</pre> <p>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.</p> <p id="index-9">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).</p> <p id="index-10">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 <em>are</em> required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.</p> </section> <section id="displays-for-lists-sets-and-dictionaries"> <span id="comprehensions"></span><h3>
<span class="section-number">6.2.4. </span>Displays for lists, sets and dictionaries</h3> <p id="index-11">For constructing a list, a set or a dictionary Python provides special syntax called “displays”, each of them in two flavors:</p> <ul class="simple"> <li>either the container contents are listed explicitly, or</li> <li>they are computed via a set of looping and filtering instructions, called a <em class="dfn">comprehension</em>.</li> </ul> <p id="index-12">Common syntax elements for comprehensions are:</p> <pre>
<strong id="grammar-token-python-grammar-comprehension"><span id="grammar-token-comprehension"></span>comprehension</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-assignment_expression">assignment_expression</a> <a class="reference internal" href="#grammar-token-python-grammar-comp_for">comp_for</a>
<strong id="grammar-token-python-grammar-comp_for"><span id="grammar-token-comp-for"></span>comp_for     </strong> ::=  ["async"] "for" <a class="reference internal" href="simple_stmts#grammar-token-python-grammar-target_list">target_list</a> "in" <a class="reference internal" href="#grammar-token-python-grammar-or_test">or_test</a> [<a class="reference internal" href="#grammar-token-python-grammar-comp_iter">comp_iter</a>]
<strong id="grammar-token-python-grammar-comp_iter"><span id="grammar-token-comp-iter"></span>comp_iter    </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-comp_for">comp_for</a> | <a class="reference internal" href="#grammar-token-python-grammar-comp_if">comp_if</a>
<strong id="grammar-token-python-grammar-comp_if"><span id="grammar-token-comp-if"></span>comp_if      </strong> ::=  "if" <a class="reference internal" href="#grammar-token-python-grammar-or_test">or_test</a> [<a class="reference internal" href="#grammar-token-python-grammar-comp_iter">comp_iter</a>]
</pre> <p>The comprehension consists of a single expression followed by at least one <code>for</code> clause and zero or more <code>for</code> or <code>if</code> clauses. In this case, the elements of the new container are those that would be produced by considering each of the <code>for</code> or <code>if</code> clauses a block, nesting from left to right, and evaluating the expression to produce an element each time the innermost block is reached.</p> <p>However, aside from the iterable expression in the leftmost <code>for</code> 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.</p> <p>The iterable expression in the leftmost <code>for</code> clause is evaluated directly in the enclosing scope and then passed as an argument to the implicitly nested scope. Subsequent <code>for</code> clauses and any filter condition in the leftmost <code>for</code> clause cannot be evaluated in the enclosing scope as they may depend on the values obtained from the leftmost iterable. For example: <code>[x*y for x in range(10) for y in range(x, x+10)]</code>.</p> <p>To ensure the comprehension always results in a container of the appropriate type, <code>yield</code> and <code>yield from</code> expressions are prohibited in the implicitly nested scope.</p> <p id="index-13">Since Python 3.6, in an <a class="reference internal" href="compound_stmts#async-def"><code>async def</code></a> function, an <code>async for</code> clause may be used to iterate over a <a class="reference internal" href="../glossary#term-asynchronous-iterator"><span class="xref std std-term">asynchronous iterator</span></a>. A comprehension in an <code>async def</code> function may consist of either a <code>for</code> or <code>async for</code> clause following the leading expression, may contain additional <code>for</code> or <code>async for</code> clauses, and may also use <a class="reference internal" href="#await"><code>await</code></a> expressions. If a comprehension contains either <code>async for</code> clauses or <code>await</code> expressions or other asynchronous comprehensions it is called an <em class="dfn">asynchronous comprehension</em>. An asynchronous comprehension may suspend the execution of the coroutine function in which it appears. See also <span class="target" id="index-14"></span><a class="pep reference external" href="https://peps.python.org/pep-0530/"><strong>PEP 530</strong></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6: </span>Asynchronous comprehensions were introduced.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span><code>yield</code> and <code>yield from</code> prohibited in the implicitly nested scope.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Asynchronous comprehensions are now allowed inside comprehensions in asynchronous functions. Outer comprehensions implicitly become asynchronous.</p> </div> </section> <section id="list-displays"> <span id="lists"></span><h3>
<span class="section-number">6.2.5. </span>List displays</h3> <p id="index-15">A list display is a possibly empty series of expressions enclosed in square brackets:</p> <pre>
<strong id="grammar-token-python-grammar-list_display"><span id="grammar-token-list-display"></span>list_display</strong> ::=  "[" [<a class="reference internal" href="#grammar-token-python-grammar-starred_list">starred_list</a> | <a class="reference internal" href="#grammar-token-python-grammar-comprehension">comprehension</a>] "]"
</pre> <p>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.</p> </section> <section id="set-displays"> <span id="set"></span><h3>
<span class="section-number">6.2.6. </span>Set displays</h3> <p id="index-16">A set display is denoted by curly braces and distinguishable from dictionary displays by the lack of colons separating keys and values:</p> <pre>
<strong id="grammar-token-python-grammar-set_display"><span id="grammar-token-set-display"></span>set_display</strong> ::=  "{" (<a class="reference internal" href="#grammar-token-python-grammar-starred_list">starred_list</a> | <a class="reference internal" href="#grammar-token-python-grammar-comprehension">comprehension</a>) "}"
</pre> <p>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.</p> <p>An empty set cannot be constructed with <code>{}</code>; this literal constructs an empty dictionary.</p> </section> <section id="dictionary-displays"> <span id="dict"></span><h3>
<span class="section-number">6.2.7. </span>Dictionary displays</h3> <p id="index-17">A dictionary display is a possibly empty series of dict items (key/value pairs) enclosed in curly braces:</p> <pre>
<strong id="grammar-token-python-grammar-dict_display"><span id="grammar-token-dict-display"></span>dict_display      </strong> ::=  "{" [<a class="reference internal" href="#grammar-token-python-grammar-dict_item_list">dict_item_list</a> | <a class="reference internal" href="#grammar-token-python-grammar-dict_comprehension">dict_comprehension</a>] "}"
<strong id="grammar-token-python-grammar-dict_item_list"><span id="grammar-token-dict-item-list"></span>dict_item_list    </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-dict_item">dict_item</a> ("," <a class="reference internal" href="#grammar-token-python-grammar-dict_item">dict_item</a>)* [","]
<strong id="grammar-token-python-grammar-dict_item"><span id="grammar-token-dict-item"></span>dict_item         </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a> ":" <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a> | "**" <a class="reference internal" href="#grammar-token-python-grammar-or_expr">or_expr</a>
<strong id="grammar-token-python-grammar-dict_comprehension"><span id="grammar-token-dict-comprehension"></span>dict_comprehension</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a> ":" <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a> <a class="reference internal" href="#grammar-token-python-grammar-comp_for">comp_for</a>
</pre> <p>A dictionary display yields a new dictionary object.</p> <p>If a comma-separated sequence of dict items 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 value. This means that you can specify the same key multiple times in the dict item list, and the final dictionary’s value for that key will be the last one given.</p> <p id="index-18">A double asterisk <code>**</code> denotes <em class="dfn">dictionary unpacking</em>. Its operand must be a <a class="reference internal" href="../glossary#term-mapping"><span class="xref std std-term">mapping</span></a>. Each mapping item is added to the new dictionary. Later values replace values already set by earlier dict items and earlier dictionary unpackings.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5: </span>Unpacking into dictionary displays, originally proposed by <span class="target" id="index-19"></span><a class="pep reference external" href="https://peps.python.org/pep-0448/"><strong>PEP 448</strong></a>.</p> </div> <p>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.</p> <p id="index-20">Restrictions on the types of the key values are listed earlier in section <a class="reference internal" href="datamodel#types"><span class="std std-ref">The standard type hierarchy</span></a>. (To summarize, the key type should be <a class="reference internal" href="../glossary#term-hashable"><span class="xref std std-term">hashable</span></a>, which excludes all mutable objects.) Clashes between duplicate keys are not detected; the last value (textually rightmost in the display) stored for a given key value prevails.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>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 <span class="target" id="index-21"></span><a class="pep reference external" href="https://peps.python.org/pep-0572/"><strong>PEP 572</strong></a>.</p> </div> </section> <section id="generator-expressions"> <span id="genexpr"></span><h3>
<span class="section-number">6.2.8. </span>Generator expressions</h3> <p id="index-22">A generator expression is a compact generator notation in parentheses:</p> <pre>
<strong id="grammar-token-python-grammar-generator_expression"><span id="grammar-token-generator-expression"></span>generator_expression</strong> ::=  "(" <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a> <a class="reference internal" href="#grammar-token-python-grammar-comp_for">comp_for</a> ")"
</pre> <p>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.</p> <p>Variables used in the generator expression are evaluated lazily when the <a class="reference internal" href="#generator.__next__" title="generator.__next__"><code>__next__()</code></a> method is called for the generator object (in the same fashion as normal generators). However, the iterable expression in the leftmost <code>for</code> 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 <code>for</code> clauses and any filter condition in the leftmost <code>for</code> clause cannot be evaluated in the enclosing scope as they may depend on the values obtained from the leftmost iterable. For example: <code>(x*y for x in range(10) for y in range(x, x+10))</code>.</p> <p>The parentheses can be omitted on calls with only one argument. See section <a class="reference internal" href="#calls"><span class="std std-ref">Calls</span></a> for details.</p> <p>To avoid interfering with the expected operation of the generator expression itself, <code>yield</code> and <code>yield from</code> expressions are prohibited in the implicitly defined generator.</p> <p>If a generator expression contains either <code>async for</code> clauses or <a class="reference internal" href="#await"><code>await</code></a> expressions it is called an <em class="dfn">asynchronous generator expression</em>. An asynchronous generator expression returns a new asynchronous generator object, which is an asynchronous iterator (see <a class="reference internal" href="datamodel#async-iterators"><span class="std std-ref">Asynchronous Iterators</span></a>).</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.6: </span>Asynchronous generator expressions were introduced.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Prior to Python 3.7, asynchronous generator expressions could only appear in <a class="reference internal" href="compound_stmts#async-def"><code>async def</code></a> coroutines. Starting with 3.7, any function can use asynchronous generator expressions.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span><code>yield</code> and <code>yield from</code> prohibited in the implicitly nested scope.</p> </div> </section> <section id="yield-expressions"> <span id="yieldexpr"></span><h3>
<span class="section-number">6.2.9. </span>Yield expressions</h3> <pre id="index-23">
<strong id="grammar-token-python-grammar-yield_atom"><span id="grammar-token-yield-atom"></span>yield_atom      </strong> ::=  "(" <a class="reference internal" href="#grammar-token-python-grammar-yield_expression">yield_expression</a> ")"
<strong id="grammar-token-python-grammar-yield_expression"><span id="grammar-token-yield-expression"></span>yield_expression</strong> ::=  "yield" [<a class="reference internal" href="#grammar-token-python-grammar-expression_list">expression_list</a> | "from" <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a>]
</pre> <p>The yield expression is used when defining a <a class="reference internal" href="../glossary#term-generator"><span class="xref std std-term">generator</span></a> function or an <a class="reference internal" href="../glossary#term-asynchronous-generator"><span class="xref std std-term">asynchronous generator</span></a> 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 <a class="reference internal" href="compound_stmts#async-def"><code>async def</code></a> function’s body causes that coroutine function to be an asynchronous generator function. For example:</p> <pre data-language="python">def gen():  # defines a generator function
    yield 123

async def agen(): # defines an asynchronous generator function
    yield 123
</pre> <p>Due to their side effects on the containing scope, <code>yield</code> expressions are not permitted as part of the implicitly defined scopes used to implement comprehensions and generator expressions.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Yield expressions prohibited in the implicitly nested scopes used to implement comprehensions and generator expressions.</p> </div> <p>Generator functions are described below, while asynchronous generator functions are described separately in section <a class="reference internal" href="#asynchronous-generator-functions"><span class="std std-ref">Asynchronous generator functions</span></a>.</p> <p>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 <a class="reference internal" href="#grammar-token-python-grammar-expression_list"><code>expression_list</code></a> to the generator’s caller, or <code>None</code> if <a class="reference internal" href="#grammar-token-python-grammar-expression_list"><code>expression_list</code></a> is omitted. 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 <a class="reference internal" href="#generator.__next__" title="generator.__next__"><code>__next__()</code></a> is used (typically via either a <a class="reference internal" href="compound_stmts#for"><code>for</code></a> or the <a class="reference internal" href="../library/functions#next" title="next"><code>next()</code></a> builtin) then the result is <a class="reference internal" href="../library/constants#None" title="None"><code>None</code></a>. Otherwise, if <a class="reference internal" href="#generator.send" title="generator.send"><code>send()</code></a> is used, then the result will be the value passed in to that method.</p> <p id="index-24">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.</p> <p>Yield expressions are allowed anywhere in a <a class="reference internal" href="compound_stmts#try"><code>try</code></a> 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 <a class="reference internal" href="#generator.close" title="generator.close"><code>close()</code></a> method will be called, allowing any pending <a class="reference internal" href="compound_stmts#finally"><code>finally</code></a> clauses to execute.</p> <p id="index-25">When <code>yield from &lt;expr&gt;</code> 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 <a class="reference internal" href="#generator.send" title="generator.send"><code>send()</code></a> and any exceptions passed in with <a class="reference internal" href="#generator.throw" title="generator.throw"><code>throw()</code></a> are passed to the underlying iterator if it has the appropriate methods. If this is not the case, then <a class="reference internal" href="#generator.send" title="generator.send"><code>send()</code></a> will raise <a class="reference internal" href="../library/exceptions#AttributeError" title="AttributeError"><code>AttributeError</code></a> or <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a>, while <a class="reference internal" href="#generator.throw" title="generator.throw"><code>throw()</code></a> will just raise the passed in exception immediately.</p> <p>When the underlying iterator is complete, the <a class="reference internal" href="../library/exceptions#StopIteration.value" title="StopIteration.value"><code>value</code></a> attribute of the raised <a class="reference internal" href="../library/exceptions#StopIteration" title="StopIteration"><code>StopIteration</code></a> instance becomes the value of the yield expression. It can be either set explicitly when raising <a class="reference internal" href="../library/exceptions#StopIteration" title="StopIteration"><code>StopIteration</code></a>, or automatically when the subiterator is a generator (by returning a value from the subgenerator).</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Added <code>yield from &lt;expr&gt;</code> to delegate control flow to a subiterator.</p> </div> <p>The parentheses may be omitted when the yield expression is the sole expression on the right hand side of an assignment statement.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>
<span class="target" id="index-26"></span><a class="pep reference external" href="https://peps.python.org/pep-0255/"><strong>PEP 255</strong></a> - Simple Generators</dt>
<dd>
<p>The proposal for adding generators and the <a class="reference internal" href="simple_stmts#yield"><code>yield</code></a> statement to Python.</p> </dd> <dt>
<span class="target" id="index-27"></span><a class="pep reference external" href="https://peps.python.org/pep-0342/"><strong>PEP 342</strong></a> - Coroutines via Enhanced Generators</dt>
<dd>
<p>The proposal to enhance the API and syntax of generators, making them usable as simple coroutines.</p> </dd> <dt>
<span class="target" id="index-28"></span><a class="pep reference external" href="https://peps.python.org/pep-0380/"><strong>PEP 380</strong></a> - Syntax for Delegating to a Subgenerator</dt>
<dd>
<p>The proposal to introduce the <code>yield_from</code> syntax, making delegation to subgenerators easy.</p> </dd> <dt>
<span class="target" id="index-29"></span><a class="pep reference external" href="https://peps.python.org/pep-0525/"><strong>PEP 525</strong></a> - Asynchronous Generators</dt>
<dd>
<p>The proposal that expanded on <span class="target" id="index-30"></span><a class="pep reference external" href="https://peps.python.org/pep-0492/"><strong>PEP 492</strong></a> by adding generator capabilities to coroutine functions.</p> </dd> </dl> </div> <section id="generator-iterator-methods"> <span id="generator-methods"></span><span id="index-31"></span><h4>
<span class="section-number">6.2.9.1. </span>Generator-iterator methods</h4> <p>This subsection describes the methods of a generator iterator. They can be used to control the execution of a generator function.</p> <p>Note that calling any of the generator methods below when the generator is already executing raises a <a class="reference internal" href="../library/exceptions#ValueError" title="ValueError"><code>ValueError</code></a> exception.</p> <span class="target" id="index-32"></span><dl class="py method"> <dt class="sig sig-object py" id="generator.__next__">
<code>generator.__next__()</code> </dt> <dd>
<p>Starts the execution of a generator function or resumes it at the last executed yield expression. When a generator function is resumed with a <a class="reference internal" href="#generator.__next__" title="generator.__next__"><code>__next__()</code></a> method, the current yield expression always evaluates to <a class="reference internal" href="../library/constants#None" title="None"><code>None</code></a>. The execution then continues to the next yield expression, where the generator is suspended again, and the value of the <a class="reference internal" href="#grammar-token-python-grammar-expression_list"><code>expression_list</code></a> is returned to <a class="reference internal" href="#generator.__next__" title="generator.__next__"><code>__next__()</code></a>’s caller. If the generator exits without yielding another value, a <a class="reference internal" href="../library/exceptions#StopIteration" title="StopIteration"><code>StopIteration</code></a> exception is raised.</p> <p>This method is normally called implicitly, e.g. by a <a class="reference internal" href="compound_stmts#for"><code>for</code></a> loop, or by the built-in <a class="reference internal" href="../library/functions#next" title="next"><code>next()</code></a> function.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="generator.send">
<code>generator.send(value)</code> </dt> <dd>
<p>Resumes the execution and “sends” a value into the generator function. The <em>value</em> argument becomes the result of the current yield expression. The <a class="reference internal" href="#generator.send" title="generator.send"><code>send()</code></a> method returns the next value yielded by the generator, or raises <a class="reference internal" href="../library/exceptions#StopIteration" title="StopIteration"><code>StopIteration</code></a> if the generator exits without yielding another value. When <a class="reference internal" href="#generator.send" title="generator.send"><code>send()</code></a> is called to start the generator, it must be called with <a class="reference internal" href="../library/constants#None" title="None"><code>None</code></a> as the argument, because there is no yield expression that could receive the value.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="generator.throw">
<code>generator.throw(value)</code> </dt> <dt class="sig sig-object py"> <span class="sig-prename descclassname">generator.</span><span class="sig-name descname">throw</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">type</span></em><span class="optional">[</span>, <em class="sig-param"><span class="n">value</span></em><span class="optional">[</span>, <em class="sig-param"><span class="n">traceback</span></em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span>
</dt> <dd>
<p>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 <a class="reference internal" href="../library/exceptions#StopIteration" title="StopIteration"><code>StopIteration</code></a> 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.</p> <p>In typical use, this is called with a single exception instance similar to the way the <a class="reference internal" href="simple_stmts#raise"><code>raise</code></a> keyword is used.</p> <p>For backwards compatibility, however, the second signature is supported, following a convention from older versions of Python. The <em>type</em> argument should be an exception class, and <em>value</em> should be an exception instance. If the <em>value</em> is not provided, the <em>type</em> constructor is called to get an instance. If <em>traceback</em> is provided, it is set on the exception, otherwise any existing <a class="reference internal" href="../library/exceptions#BaseException.__traceback__" title="BaseException.__traceback__"><code>__traceback__</code></a> attribute stored in <em>value</em> may be cleared.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>The second signature (type[, value[, traceback]]) is deprecated and may be removed in a future version of Python.</p> </div> </dd>
</dl> <span class="target" id="index-33"></span><dl class="py method"> <dt class="sig sig-object py" id="generator.close">
<code>generator.close()</code> </dt> <dd>
<p>Raises a <a class="reference internal" href="../library/exceptions#GeneratorExit" title="GeneratorExit"><code>GeneratorExit</code></a> at the point where the generator function was paused. If the generator function then exits gracefully, is already closed, or raises <a class="reference internal" href="../library/exceptions#GeneratorExit" title="GeneratorExit"><code>GeneratorExit</code></a> (by not catching the exception), close returns to its caller. If the generator yields a value, a <a class="reference internal" href="../library/exceptions#RuntimeError" title="RuntimeError"><code>RuntimeError</code></a> is raised. If the generator raises any other exception, it is propagated to the caller. <a class="reference internal" href="#generator.close" title="generator.close"><code>close()</code></a> does nothing if the generator has already exited due to an exception or normal exit.</p> </dd>
</dl> </section> <section id="examples"> <span id="index-34"></span><h4>
<span class="section-number">6.2.9.2. </span>Examples</h4> <p>Here is a simple example that demonstrates the behavior of generators and generator functions:</p> <pre data-language="python">&gt;&gt;&gt; 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.")
...
&gt;&gt;&gt; generator = echo(1)
&gt;&gt;&gt; print(next(generator))
Execution starts when 'next()' is called for the first time.
1
&gt;&gt;&gt; print(next(generator))
None
&gt;&gt;&gt; print(generator.send(2))
2
&gt;&gt;&gt; generator.throw(TypeError, "spam")
TypeError('spam',)
&gt;&gt;&gt; generator.close()
Don't forget to clean up when 'close()' is called.
</pre> <p>For examples using <code>yield from</code>, see <a class="reference internal" href="https://docs.python.org/3.12/whatsnew/3.3.html#pep-380"><span class="std std-ref">PEP 380: Syntax for Delegating to a Subgenerator</span></a> in “What’s New in Python.”</p> </section> <section id="asynchronous-generator-functions"> <span id="id3"></span><h4>
<span class="section-number">6.2.9.3. </span>Asynchronous generator functions</h4> <p>The presence of a yield expression in a function or method defined using <a class="reference internal" href="compound_stmts#async-def"><code>async def</code></a> further defines the function as an <a class="reference internal" href="../glossary#term-asynchronous-generator"><span class="xref std std-term">asynchronous generator</span></a> function.</p> <p>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 <a class="reference internal" href="compound_stmts#async-for"><code>async for</code></a> statement in a coroutine function analogously to how a generator object would be used in a <a class="reference internal" href="compound_stmts#for"><code>for</code></a> statement.</p> <p>Calling one of the asynchronous generator’s methods returns an <a class="reference internal" href="../glossary#term-awaitable"><span class="xref std std-term">awaitable</span></a> 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 <a class="reference internal" href="#grammar-token-python-grammar-expression_list"><code>expression_list</code></a> 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 <a class="reference internal" href="#agen.__anext__" title="agen.__anext__"><code>__anext__()</code></a> is used then the result is <a class="reference internal" href="../library/constants#None" title="None"><code>None</code></a>. Otherwise, if <a class="reference internal" href="#agen.asend" title="agen.asend"><code>asend()</code></a> is used, then the result will be the value passed in to that method.</p> <p>If an asynchronous generator happens to exit early by <a class="reference internal" href="simple_stmts#break"><code>break</code></a>, 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 <a class="reference internal" href="#agen.aclose" title="agen.aclose"><code>aclose()</code></a> method to finalize the generator and ultimately detach it from the event loop.</p> <p>In an asynchronous generator function, yield expressions are allowed anywhere in a <a class="reference internal" href="compound_stmts#try"><code>try</code></a> 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 <code>try</code> construct could result in a failure to execute pending <a class="reference internal" href="compound_stmts#finally"><code>finally</code></a> 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 <a class="reference internal" href="#agen.aclose" title="agen.aclose"><code>aclose()</code></a> method and run the resulting coroutine object, thus allowing any pending <code>finally</code> clauses to execute.</p> <p>To take care of finalization upon event loop termination, an event loop should define a <em>finalizer</em> function which takes an asynchronous generator-iterator and presumably calls <a class="reference internal" href="#agen.aclose" title="agen.aclose"><code>aclose()</code></a> and executes the coroutine. This <em>finalizer</em> may be registered by calling <a class="reference internal" href="../library/sys#sys.set_asyncgen_hooks" title="sys.set_asyncgen_hooks"><code>sys.set_asyncgen_hooks()</code></a>. When first iterated over, an asynchronous generator-iterator will store the registered <em>finalizer</em> to be called upon finalization. For a reference example of a <em>finalizer</em> method see the implementation of <code>asyncio.Loop.shutdown_asyncgens</code> in <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/asyncio/base_events.py">Lib/asyncio/base_events.py</a>.</p> <p>The expression <code>yield from &lt;expr&gt;</code> is a syntax error when used in an asynchronous generator function.</p> </section> <section id="asynchronous-generator-iterator-methods"> <span id="asynchronous-generator-methods"></span><span id="index-35"></span><h4>
<span class="section-number">6.2.9.4. </span>Asynchronous generator-iterator methods</h4> <p>This subsection describes the methods of an asynchronous generator iterator, which are used to control the execution of a generator function.</p> <span class="target" id="index-36"></span><dl class="py method"> <dt class="sig sig-object py" id="agen.__anext__">
<code>coroutine agen.__anext__()</code> </dt> <dd>
<p>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 <a class="reference internal" href="#agen.__anext__" title="agen.__anext__"><code>__anext__()</code></a> method, the current yield expression always evaluates to <a class="reference internal" href="../library/constants#None" title="None"><code>None</code></a> in the returned awaitable, which when run will continue to the next yield expression. The value of the <a class="reference internal" href="#grammar-token-python-grammar-expression_list"><code>expression_list</code></a> of the yield expression is the value of the <a class="reference internal" href="../library/exceptions#StopIteration" title="StopIteration"><code>StopIteration</code></a> exception raised by the completing coroutine. If the asynchronous generator exits without yielding another value, the awaitable instead raises a <a class="reference internal" href="../library/exceptions#StopAsyncIteration" title="StopAsyncIteration"><code>StopAsyncIteration</code></a> exception, signalling that the asynchronous iteration has completed.</p> <p>This method is normally called implicitly by a <a class="reference internal" href="compound_stmts#async-for"><code>async for</code></a> loop.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="agen.asend">
<code>coroutine agen.asend(value)</code> </dt> <dd>
<p>Returns an awaitable which when run resumes the execution of the asynchronous generator. As with the <a class="reference internal" href="#generator.send" title="generator.send"><code>send()</code></a> method for a generator, this “sends” a value into the asynchronous generator function, and the <em>value</em> argument becomes the result of the current yield expression. The awaitable returned by the <a class="reference internal" href="#agen.asend" title="agen.asend"><code>asend()</code></a> method will return the next value yielded by the generator as the value of the raised <a class="reference internal" href="../library/exceptions#StopIteration" title="StopIteration"><code>StopIteration</code></a>, or raises <a class="reference internal" href="../library/exceptions#StopAsyncIteration" title="StopAsyncIteration"><code>StopAsyncIteration</code></a> if the asynchronous generator exits without yielding another value. When <a class="reference internal" href="#agen.asend" title="agen.asend"><code>asend()</code></a> is called to start the asynchronous generator, it must be called with <a class="reference internal" href="../library/constants#None" title="None"><code>None</code></a> as the argument, because there is no yield expression that could receive the value.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="agen.athrow">
<code>coroutine agen.athrow(value)</code> </dt> <dt class="sig sig-object py"> <em class="property">coroutine </em><span class="sig-prename descclassname">agen.</span><span class="sig-name descname">athrow</span><span class="sig-paren">(</span><em class="sig-param"><span class="n">type</span></em><span class="optional">[</span>, <em class="sig-param"><span class="n">value</span></em><span class="optional">[</span>, <em class="sig-param"><span class="n">traceback</span></em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span>
</dt> <dd>
<p>Returns an awaitable that raises an exception of type <code>type</code> 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 <a class="reference internal" href="../library/exceptions#StopIteration" title="StopIteration"><code>StopIteration</code></a> exception. If the asynchronous generator exits without yielding another value, a <a class="reference internal" href="../library/exceptions#StopAsyncIteration" title="StopAsyncIteration"><code>StopAsyncIteration</code></a> 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.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>The second signature (type[, value[, traceback]]) is deprecated and may be removed in a future version of Python.</p> </div> </dd>
</dl> <span class="target" id="index-37"></span><dl class="py method"> <dt class="sig sig-object py" id="agen.aclose">
<code>coroutine agen.aclose()</code> </dt> <dd>
<p>Returns an awaitable that when run will throw a <a class="reference internal" href="../library/exceptions#GeneratorExit" title="GeneratorExit"><code>GeneratorExit</code></a> 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 <a class="reference internal" href="../library/exceptions#GeneratorExit" title="GeneratorExit"><code>GeneratorExit</code></a> (by not catching the exception), then the returned awaitable will raise a <a class="reference internal" href="../library/exceptions#StopIteration" title="StopIteration"><code>StopIteration</code></a> exception. Any further awaitables returned by subsequent calls to the asynchronous generator will raise a <a class="reference internal" href="../library/exceptions#StopAsyncIteration" title="StopAsyncIteration"><code>StopAsyncIteration</code></a> exception. If the asynchronous generator yields a value, a <a class="reference internal" href="../library/exceptions#RuntimeError" title="RuntimeError"><code>RuntimeError</code></a> 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 <a class="reference internal" href="#agen.aclose" title="agen.aclose"><code>aclose()</code></a> will return an awaitable that does nothing.</p> </dd>
</dl> </section> </section> </section> <section id="primaries"> <span id="id4"></span><h2>
<span class="section-number">6.3. </span>Primaries</h2> <p id="index-38">Primaries represent the most tightly bound operations of the language. Their syntax is:</p> <pre>
<strong id="grammar-token-python-grammar-primary"><span id="grammar-token-primary"></span>primary</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-atom">atom</a> | <a class="reference internal" href="#grammar-token-python-grammar-attributeref">attributeref</a> | <a class="reference internal" href="#grammar-token-python-grammar-subscription">subscription</a> | <a class="reference internal" href="#grammar-token-python-grammar-slicing">slicing</a> | <a class="reference internal" href="#grammar-token-python-grammar-call">call</a>
</pre> <section id="attribute-references"> <span id="id5"></span><h3>
<span class="section-number">6.3.1. </span>Attribute references</h3> <p id="index-39">An attribute reference is a primary followed by a period and a name:</p> <pre>
<strong id="grammar-token-python-grammar-attributeref"><span id="grammar-token-attributeref"></span>attributeref</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-primary">primary</a> "." <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-identifier">identifier</a>
</pre> <p id="index-40">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.</p> <p>This production can be customized by overriding the <a class="reference internal" href="datamodel#object.__getattribute__" title="object.__getattribute__"><code>__getattribute__()</code></a> method or the <a class="reference internal" href="datamodel#object.__getattr__" title="object.__getattr__"><code>__getattr__()</code></a> method. The <code>__getattribute__()</code> method is called first and either returns a value or raises <a class="reference internal" href="../library/exceptions#AttributeError" title="AttributeError"><code>AttributeError</code></a> if the attribute is not available.</p> <p>If an <a class="reference internal" href="../library/exceptions#AttributeError" title="AttributeError"><code>AttributeError</code></a> is raised and the object has a <code>__getattr__()</code> method, that method is called as a fallback.</p> </section> <section id="subscriptions"> <span id="id6"></span><h3>
<span class="section-number">6.3.2. </span>Subscriptions</h3> <span class="target" id="index-41"></span><p id="index-42">The subscription of an instance of a <a class="reference internal" href="datamodel#sequence-types"><span class="std std-ref">container class</span></a> will generally select an element from the container. The subscription of a <a class="reference internal" href="../glossary#term-generic-type"><span class="xref std std-term">generic class</span></a> will generally return a <a class="reference internal" href="../library/stdtypes#types-genericalias"><span class="std std-ref">GenericAlias</span></a> object.</p> <pre>
<strong id="grammar-token-python-grammar-subscription"><span id="grammar-token-subscription"></span>subscription</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-primary">primary</a> "[" <a class="reference internal" href="#grammar-token-python-grammar-expression_list">expression_list</a> "]"
</pre> <p>When an object is subscripted, the interpreter will evaluate the primary and the expression list.</p> <p>The primary must evaluate to an object that supports subscription. An object may support subscription through defining one or both of <a class="reference internal" href="datamodel#object.__getitem__" title="object.__getitem__"><code>__getitem__()</code></a> and <a class="reference internal" href="datamodel#object.__class_getitem__" title="object.__class_getitem__"><code>__class_getitem__()</code></a>. 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 <code>__class_getitem__</code> is called instead of <code>__getitem__</code>, see <a class="reference internal" href="datamodel#classgetitem-versus-getitem"><span class="std std-ref">__class_getitem__ versus __getitem__</span></a>.</p> <p>If the expression list contains at least one comma, it will evaluate to a <a class="reference internal" href="../library/stdtypes#tuple" title="tuple"><code>tuple</code></a> containing the items of the expression list. Otherwise, the expression list will evaluate to the value of the list’s sole member.</p> <p>For built-in objects, there are two types of objects that support subscription via <a class="reference internal" href="datamodel#object.__getitem__" title="object.__getitem__"><code>__getitem__()</code></a>:</p> <ol class="arabic simple"> <li>Mappings. If the primary is a <a class="reference internal" href="../glossary#term-mapping"><span class="xref std std-term">mapping</span></a>, 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 <a class="reference internal" href="../library/stdtypes#dict" title="dict"><code>dict</code></a> class.</li> <li>Sequences. If the primary is a <a class="reference internal" href="../glossary#term-sequence"><span class="xref std std-term">sequence</span></a>, the expression list must evaluate to an <a class="reference internal" href="../library/functions#int" title="int"><code>int</code></a> or a <a class="reference internal" href="../library/functions#slice" title="slice"><code>slice</code></a> (as discussed in the following section). Examples of builtin sequence classes include the <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str</code></a>, <a class="reference internal" href="../library/stdtypes#list" title="list"><code>list</code></a> and <a class="reference internal" href="../library/stdtypes#tuple" title="tuple"><code>tuple</code></a> classes.</li> </ol> <p>The formal syntax makes no special provision for negative indices in <a class="reference internal" href="../glossary#term-sequence"><span class="xref std std-term">sequences</span></a>. However, built-in sequences all provide a <a class="reference internal" href="datamodel#object.__getitem__" title="object.__getitem__"><code>__getitem__()</code></a> method that interprets negative indices by adding the length of the sequence to the index so that, for example, <code>x[-1]</code> selects the last item of <code>x</code>. 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 <a class="reference internal" href="datamodel#object.__getitem__" title="object.__getitem__"><code>__getitem__()</code></a> method, subclasses overriding this method will need to explicitly add that support.</p> <p id="index-43">A <a class="reference internal" href="../library/stdtypes#str" title="str"><code>string</code></a> is a special kind of sequence whose items are <em>characters</em>. A character is not a separate data type but a string of exactly one character.</p> </section> <section id="slicings"> <span id="id7"></span><h3>
<span class="section-number">6.3.3. </span>Slicings</h3> <span class="target" id="index-44"></span><p id="index-45">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 <a class="reference internal" href="simple_stmts#del"><code>del</code></a> statements. The syntax for a slicing:</p> <pre>
<strong id="grammar-token-python-grammar-slicing"><span id="grammar-token-slicing"></span>slicing     </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-primary">primary</a> "[" <a class="reference internal" href="#grammar-token-python-grammar-slice_list">slice_list</a> "]"
<strong id="grammar-token-python-grammar-slice_list"><span id="grammar-token-slice-list"></span>slice_list  </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-slice_item">slice_item</a> ("," <a class="reference internal" href="#grammar-token-python-grammar-slice_item">slice_item</a>)* [","]
<strong id="grammar-token-python-grammar-slice_item"><span id="grammar-token-slice-item"></span>slice_item  </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a> | <a class="reference internal" href="#grammar-token-python-grammar-proper_slice">proper_slice</a>
<strong id="grammar-token-python-grammar-proper_slice"><span id="grammar-token-proper-slice"></span>proper_slice</strong> ::=  [<a class="reference internal" href="#grammar-token-python-grammar-lower_bound">lower_bound</a>] ":" [<a class="reference internal" href="#grammar-token-python-grammar-upper_bound">upper_bound</a>] [ ":" [<a class="reference internal" href="#grammar-token-python-grammar-stride">stride</a>] ]
<strong id="grammar-token-python-grammar-lower_bound"><span id="grammar-token-lower-bound"></span>lower_bound </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a>
<strong id="grammar-token-python-grammar-upper_bound"><span id="grammar-token-upper-bound"></span>upper_bound </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a>
<strong id="grammar-token-python-grammar-stride"><span id="grammar-token-stride"></span>stride      </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a>
</pre> <p>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).</p> <p id="index-46">The semantics for a slicing are as follows. The primary is indexed (using the same <a class="reference internal" href="datamodel#object.__getitem__" title="object.__getitem__"><code>__getitem__()</code></a> 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 <a class="reference internal" href="datamodel#types"><span class="std std-ref">The standard type hierarchy</span></a>) whose <a class="reference internal" href="../library/functions#slice.start" title="slice.start"><code>start</code></a>, <a class="reference internal" href="../library/functions#slice.stop" title="slice.stop"><code>stop</code></a> and <a class="reference internal" href="../library/functions#slice.step" title="slice.step"><code>step</code></a> attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting <code>None</code> for missing expressions.</p> </section> <section id="calls"> <span id="index-47"></span><span id="id8"></span><h3>
<span class="section-number">6.3.4. </span>Calls</h3> <p>A call calls a callable object (e.g., a <a class="reference internal" href="../glossary#term-function"><span class="xref std std-term">function</span></a>) with a possibly empty series of <a class="reference internal" href="../glossary#term-argument"><span class="xref std std-term">arguments</span></a>:</p> <pre>
<strong id="grammar-token-python-grammar-call"><span id="grammar-token-call"></span>call                </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-primary">primary</a> "(" [<a class="reference internal" href="#grammar-token-python-grammar-argument_list">argument_list</a> [","] | <a class="reference internal" href="#grammar-token-python-grammar-comprehension">comprehension</a>] ")"
<strong id="grammar-token-python-grammar-argument_list"><span id="grammar-token-argument-list"></span>argument_list       </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-positional_arguments">positional_arguments</a> ["," <a class="reference internal" href="#grammar-token-python-grammar-starred_and_keywords">starred_and_keywords</a>]
                            ["," <a class="reference internal" href="#grammar-token-python-grammar-keywords_arguments">keywords_arguments</a>]
                          | <a class="reference internal" href="#grammar-token-python-grammar-starred_and_keywords">starred_and_keywords</a> ["," <a class="reference internal" href="#grammar-token-python-grammar-keywords_arguments">keywords_arguments</a>]
                          | <a class="reference internal" href="#grammar-token-python-grammar-keywords_arguments">keywords_arguments</a>
<strong id="grammar-token-python-grammar-positional_arguments"><span id="grammar-token-positional-arguments"></span>positional_arguments</strong> ::=  positional_item ("," positional_item)*
<strong id="grammar-token-python-grammar-positional_item"><span id="grammar-token-positional-item"></span>positional_item     </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-assignment_expression">assignment_expression</a> | "*" <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a>
<strong id="grammar-token-python-grammar-starred_and_keywords"><span id="grammar-token-starred-and-keywords"></span>starred_and_keywords</strong> ::=  ("*" <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a> | <a class="reference internal" href="#grammar-token-python-grammar-keyword_item">keyword_item</a>)
                          ("," "*" <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a> | "," <a class="reference internal" href="#grammar-token-python-grammar-keyword_item">keyword_item</a>)*
<strong id="grammar-token-python-grammar-keywords_arguments"><span id="grammar-token-keywords-arguments"></span>keywords_arguments  </strong> ::=  (<a class="reference internal" href="#grammar-token-python-grammar-keyword_item">keyword_item</a> | "**" <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a>)
                          ("," <a class="reference internal" href="#grammar-token-python-grammar-keyword_item">keyword_item</a> | "," "**" <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a>)*
<strong id="grammar-token-python-grammar-keyword_item"><span id="grammar-token-keyword-item"></span>keyword_item        </strong> ::=  <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-identifier">identifier</a> "=" <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a>
</pre> <p>An optional trailing comma may be present after the positional and keyword arguments but does not affect the semantics.</p> <p id="index-48">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 <code>__call__()</code> method are callable). All argument expressions are evaluated before the call is attempted. Please refer to section <a class="reference internal" href="compound_stmts#function"><span class="std std-ref">Function definitions</span></a> for the syntax of formal <a class="reference internal" href="../glossary#term-parameter"><span class="xref std std-term">parameter</span></a> lists.</p> <p>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 <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> exception is raised. Otherwise, the argument is placed in the slot, filling it (even if the expression is <code>None</code>, 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 <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> exception is raised. Otherwise, the list of filled slots is used as the argument list for the call.</p> <div class="impl-detail compound"> <p><strong>CPython implementation detail:</strong> 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 <a class="reference internal" href="../c-api/arg#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code>PyArg_ParseTuple()</code></a> to parse their arguments.</p> </div> <p>If there are more positional arguments than there are formal parameter slots, a <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> exception is raised, unless a formal parameter using the syntax <code>*identifier</code> 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).</p> <p>If any keyword argument does not correspond to a formal parameter name, a <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> exception is raised, unless a formal parameter using the syntax <code>**identifier</code> 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.</p> <p id="index-49">If the syntax <code>*expression</code> appears in the function call, <code>expression</code> must evaluate to an <a class="reference internal" href="../glossary#term-iterable"><span class="xref std std-term">iterable</span></a>. Elements from these iterables are treated as if they were additional positional arguments. For the call <code>f(x1, x2, *y, x3, x4)</code>, if <em>y</em> evaluates to a sequence <em>y1</em>, …, <em>yM</em>, this is equivalent to a call with M+4 positional arguments <em>x1</em>, <em>x2</em>, <em>y1</em>, …, <em>yM</em>, <em>x3</em>, <em>x4</em>.</p> <p>A consequence of this is that although the <code>*expression</code> syntax may appear <em>after</em> explicit keyword arguments, it is processed <em>before</em> the keyword arguments (and any <code>**expression</code> arguments – see below). So:</p> <pre data-language="python">&gt;&gt;&gt; def f(a, b):
...     print(a, b)
...
&gt;&gt;&gt; f(b=1, *(2,))
2 1
&gt;&gt;&gt; f(a=1, *(2,))
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
TypeError: f() got multiple values for keyword argument 'a'
&gt;&gt;&gt; f(1, *(2,))
1 2
</pre> <p>It is unusual for both keyword arguments and the <code>*expression</code> syntax to be used in the same call, so in practice this confusion does not often arise.</p> <p id="index-50">If the syntax <code>**expression</code> appears in the function call, <code>expression</code> must evaluate to a <a class="reference internal" href="../glossary#term-mapping"><span class="xref std std-term">mapping</span></a>, 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 <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> exception is raised.</p> <p>When <code>**expression</code> 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. <code>"max-temp °F"</code> 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 <code>**</code> parameter, if there is one, or if there is not, a <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> exception is raised.</p> <p>Formal parameters using the syntax <code>*identifier</code> or <code>**identifier</code> cannot be used as positional argument slots or as keyword argument names.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Function calls accept any number of <code>*</code> and <code>**</code> unpackings, positional arguments may follow iterable unpackings (<code>*</code>), and keyword arguments may follow dictionary unpackings (<code>**</code>). Originally proposed by <span class="target" id="index-51"></span><a class="pep reference external" href="https://peps.python.org/pep-0448/"><strong>PEP 448</strong></a>.</p> </div> <p>A call always returns some value, possibly <code>None</code>, unless it raises an exception. How this value is computed depends on the type of the callable object.</p> <p>If it is—</p> <dl> <dt>a user-defined function:</dt>
<dd>
<p id="index-52">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 <a class="reference internal" href="compound_stmts#function"><span class="std std-ref">Function definitions</span></a>. When the code block executes a <a class="reference internal" href="simple_stmts#return"><code>return</code></a> statement, this specifies the return value of the function call.</p> </dd> <dt>a built-in function or method:</dt>
<dd>
<p id="index-53">The result is up to the interpreter; see <a class="reference internal" href="../library/functions#built-in-funcs"><span class="std std-ref">Built-in Functions</span></a> for the descriptions of built-in functions and methods.</p> </dd> <dt>a class object:</dt>
<dd>
<p id="index-54">A new instance of that class is returned.</p> </dd> <dt>a class instance method:</dt>
<dd>
<p id="index-55">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.</p> </dd> <dt>a class instance:</dt>
<dd>
<p id="index-56">The class must define a <code>__call__()</code> method; the effect is then the same as if that method was called.</p> </dd> </dl> </section> </section> <section id="await-expression"> <span id="await"></span><span id="index-57"></span><h2>
<span class="section-number">6.4. </span>Await expression</h2> <p>Suspend the execution of <a class="reference internal" href="../glossary#term-coroutine"><span class="xref std std-term">coroutine</span></a> on an <a class="reference internal" href="../glossary#term-awaitable"><span class="xref std std-term">awaitable</span></a> object. Can only be used inside a <a class="reference internal" href="../glossary#term-coroutine-function"><span class="xref std std-term">coroutine function</span></a>.</p> <pre>
<strong id="grammar-token-python-grammar-await_expr"><span id="grammar-token-await-expr"></span>await_expr</strong> ::=  "await" <a class="reference internal" href="#grammar-token-python-grammar-primary">primary</a>
</pre> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> </section> <section id="the-power-operator"> <span id="power"></span><h2>
<span class="section-number">6.5. </span>The power operator</h2> <p id="index-58">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:</p> <pre>
<strong id="grammar-token-python-grammar-power"><span id="grammar-token-power"></span>power</strong> ::=  (<a class="reference internal" href="#grammar-token-python-grammar-await_expr">await_expr</a> | <a class="reference internal" href="#grammar-token-python-grammar-primary">primary</a>) ["**" <a class="reference internal" href="#grammar-token-python-grammar-u_expr">u_expr</a>]
</pre> <p>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): <code>-1**2</code> results in <code>-1</code>.</p> <p>The power operator has the same semantics as the built-in <a class="reference internal" href="../library/functions#pow" title="pow"><code>pow()</code></a> 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.</p> <p>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, <code>10**2</code> returns <code>100</code>, but <code>10**-2</code> returns <code>0.01</code>.</p> <p>Raising <code>0.0</code> to a negative power results in a <a class="reference internal" href="../library/exceptions#ZeroDivisionError" title="ZeroDivisionError"><code>ZeroDivisionError</code></a>. Raising a negative number to a fractional power results in a <a class="reference internal" href="../library/functions#complex" title="complex"><code>complex</code></a> number. (In earlier versions it raised a <a class="reference internal" href="../library/exceptions#ValueError" title="ValueError"><code>ValueError</code></a>.)</p> <p>This operation can be customized using the special <code>__pow__()</code> method.</p> </section> <section id="unary-arithmetic-and-bitwise-operations"> <span id="unary"></span><h2>
<span class="section-number">6.6. </span>Unary arithmetic and bitwise operations</h2> <p id="index-59">All unary arithmetic and bitwise operations have the same priority:</p> <pre>
<strong id="grammar-token-python-grammar-u_expr"><span id="grammar-token-u-expr"></span>u_expr</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-power">power</a> | "-" <a class="reference internal" href="#grammar-token-python-grammar-u_expr">u_expr</a> | "+" <a class="reference internal" href="#grammar-token-python-grammar-u_expr">u_expr</a> | "~" <a class="reference internal" href="#grammar-token-python-grammar-u_expr">u_expr</a>
</pre> <p id="index-60">The unary <code>-</code> (minus) operator yields the negation of its numeric argument; the operation can be overridden with the <code>__neg__()</code> special method.</p> <p id="index-61">The unary <code>+</code> (plus) operator yields its numeric argument unchanged; the operation can be overridden with the <code>__pos__()</code> special method.</p> <p id="index-62">The unary <code>~</code> (invert) operator yields the bitwise inversion of its integer argument. The bitwise inversion of <code>x</code> is defined as <code>-(x+1)</code>. It only applies to integral numbers or to custom objects that override the <code>__invert__()</code> special method.</p> <p id="index-63">In all three cases, if the argument does not have the proper type, a <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> exception is raised.</p> </section> <section id="binary-arithmetic-operations"> <span id="binary"></span><h2>
<span class="section-number">6.7. </span>Binary arithmetic operations</h2> <p id="index-64">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:</p> <pre>
<strong id="grammar-token-python-grammar-m_expr"><span id="grammar-token-m-expr"></span>m_expr</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-u_expr">u_expr</a> | <a class="reference internal" href="#grammar-token-python-grammar-m_expr">m_expr</a> "*" <a class="reference internal" href="#grammar-token-python-grammar-u_expr">u_expr</a> | <a class="reference internal" href="#grammar-token-python-grammar-m_expr">m_expr</a> "@" <a class="reference internal" href="#grammar-token-python-grammar-m_expr">m_expr</a> |
            <a class="reference internal" href="#grammar-token-python-grammar-m_expr">m_expr</a> "//" <a class="reference internal" href="#grammar-token-python-grammar-u_expr">u_expr</a> | <a class="reference internal" href="#grammar-token-python-grammar-m_expr">m_expr</a> "/" <a class="reference internal" href="#grammar-token-python-grammar-u_expr">u_expr</a> |
            <a class="reference internal" href="#grammar-token-python-grammar-m_expr">m_expr</a> "%" <a class="reference internal" href="#grammar-token-python-grammar-u_expr">u_expr</a>
<strong id="grammar-token-python-grammar-a_expr"><span id="grammar-token-a-expr"></span>a_expr</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-m_expr">m_expr</a> | <a class="reference internal" href="#grammar-token-python-grammar-a_expr">a_expr</a> "+" <a class="reference internal" href="#grammar-token-python-grammar-m_expr">m_expr</a> | <a class="reference internal" href="#grammar-token-python-grammar-a_expr">a_expr</a> "-" <a class="reference internal" href="#grammar-token-python-grammar-m_expr">m_expr</a>
</pre> <p id="index-65">The <code>*</code> (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.</p> <p>This operation can be customized using the special <code>__mul__()</code> and <code>__rmul__()</code> methods.</p> <p id="index-66">The <code>@</code> (at) operator is intended to be used for matrix multiplication. No builtin Python types implement this operator.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5.</span></p> </div> <p id="index-67">The <code>/</code> (division) and <code>//</code> (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 <a class="reference internal" href="../library/exceptions#ZeroDivisionError" title="ZeroDivisionError"><code>ZeroDivisionError</code></a> exception.</p> <p>This operation can be customized using the special <code>__truediv__()</code> and <code>__floordiv__()</code> methods.</p> <p id="index-68">The <code>%</code> (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 <a class="reference internal" href="../library/exceptions#ZeroDivisionError" title="ZeroDivisionError"><code>ZeroDivisionError</code></a> exception. The arguments may be floating point numbers, e.g., <code>3.14%0.7</code> equals <code>0.34</code> (since <code>3.14</code> equals <code>4*0.7 + 0.34</code>.) 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 <a class="footnote-reference brackets" href="#id17" id="id9">1</a>.</p> <p>The floor division and modulo operators are connected by the following identity: <code>x == (x//y)*y + (x%y)</code>. Floor division and modulo are also connected with the built-in function <a class="reference internal" href="../library/functions#divmod" title="divmod"><code>divmod()</code></a>: <code>divmod(x, y) == (x//y,
x%y)</code>. <a class="footnote-reference brackets" href="#id18" id="id10">2</a>.</p> <p>In addition to performing the modulo operation on numbers, the <code>%</code> 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 <a class="reference internal" href="../library/stdtypes#old-string-formatting"><span class="std std-ref">printf-style String Formatting</span></a>.</p> <p>The <em>modulo</em> operation can be customized using the special <code>__mod__()</code> method.</p> <p>The floor division operator, the modulo operator, and the <a class="reference internal" href="../library/functions#divmod" title="divmod"><code>divmod()</code></a> function are not defined for complex numbers. Instead, convert to a floating point number using the <a class="reference internal" href="../library/functions#abs" title="abs"><code>abs()</code></a> function if appropriate.</p> <p id="index-69">The <code>+</code> (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.</p> <p>This operation can be customized using the special <code>__add__()</code> and <code>__radd__()</code> methods.</p> <p id="index-70">The <code>-</code> (subtraction) operator yields the difference of its arguments. The numeric arguments are first converted to a common type.</p> <p>This operation can be customized using the special <code>__sub__()</code> method.</p> </section> <section id="shifting-operations"> <span id="shifting"></span><h2>
<span class="section-number">6.8. </span>Shifting operations</h2> <p id="index-71">The shifting operations have lower priority than the arithmetic operations:</p> <pre>
<strong id="grammar-token-python-grammar-shift_expr"><span id="grammar-token-shift-expr"></span>shift_expr</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-a_expr">a_expr</a> | <a class="reference internal" href="#grammar-token-python-grammar-shift_expr">shift_expr</a> ("&lt;&lt;" | "&gt;&gt;") <a class="reference internal" href="#grammar-token-python-grammar-a_expr">a_expr</a>
</pre> <p>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.</p> <p>This operation can be customized using the special <code>__lshift__()</code> and <code>__rshift__()</code> methods.</p> <p id="index-72">A right shift by <em>n</em> bits is defined as floor division by <code>pow(2,n)</code>. A left shift by <em>n</em> bits is defined as multiplication with <code>pow(2,n)</code>.</p> </section> <section id="binary-bitwise-operations"> <span id="bitwise"></span><h2>
<span class="section-number">6.9. </span>Binary bitwise operations</h2> <p id="index-73">Each of the three bitwise operations has a different priority level:</p> <pre>
<strong id="grammar-token-python-grammar-and_expr"><span id="grammar-token-and-expr"></span>and_expr</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-shift_expr">shift_expr</a> | <a class="reference internal" href="#grammar-token-python-grammar-and_expr">and_expr</a> "&amp;" <a class="reference internal" href="#grammar-token-python-grammar-shift_expr">shift_expr</a>
<strong id="grammar-token-python-grammar-xor_expr"><span id="grammar-token-xor-expr"></span>xor_expr</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-and_expr">and_expr</a> | <a class="reference internal" href="#grammar-token-python-grammar-xor_expr">xor_expr</a> "^" <a class="reference internal" href="#grammar-token-python-grammar-and_expr">and_expr</a>
<strong id="grammar-token-python-grammar-or_expr"><span id="grammar-token-or-expr"></span>or_expr </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-xor_expr">xor_expr</a> | <a class="reference internal" href="#grammar-token-python-grammar-or_expr">or_expr</a> "|" <a class="reference internal" href="#grammar-token-python-grammar-xor_expr">xor_expr</a>
</pre> <p id="index-74">The <code>&amp;</code> operator yields the bitwise AND of its arguments, which must be integers or one of them must be a custom object overriding <code>__and__()</code> or <code>__rand__()</code> special methods.</p> <p id="index-75">The <code>^</code> operator yields the bitwise XOR (exclusive OR) of its arguments, which must be integers or one of them must be a custom object overriding <code>__xor__()</code> or <code>__rxor__()</code> special methods.</p> <p id="index-76">The <code>|</code> operator yields the bitwise (inclusive) OR of its arguments, which must be integers or one of them must be a custom object overriding <code>__or__()</code> or <code>__ror__()</code> special methods.</p> </section> <section id="comparisons"> <span id="id11"></span><h2>
<span class="section-number">6.10. </span>Comparisons</h2> <p id="index-77">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 <code>a &lt; b &lt; c</code> have the interpretation that is conventional in mathematics:</p> <pre>
<strong id="grammar-token-python-grammar-comparison"><span id="grammar-token-comparison"></span>comparison   </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-or_expr">or_expr</a> (<a class="reference internal" href="#grammar-token-python-grammar-comp_operator">comp_operator</a> <a class="reference internal" href="#grammar-token-python-grammar-or_expr">or_expr</a>)*
<strong id="grammar-token-python-grammar-comp_operator"><span id="grammar-token-comp-operator"></span>comp_operator</strong> ::=  "&lt;" | "&gt;" | "==" | "&gt;=" | "&lt;=" | "!="
                   | "is" ["not"] | ["not"] "in"
</pre> <p>Comparisons yield boolean values: <code>True</code> or <code>False</code>. Custom <em class="dfn">rich comparison methods</em> may return non-boolean values. In this case Python will call <a class="reference internal" href="../library/functions#bool" title="bool"><code>bool()</code></a> on such value in boolean contexts.</p> <p id="index-78">Comparisons can be chained arbitrarily, e.g., <code>x &lt; y &lt;= z</code> is equivalent to <code>x &lt; y and y &lt;= z</code>, except that <code>y</code> is evaluated only once (but in both cases <code>z</code> is not evaluated at all when <code>x &lt; y</code> is found to be false).</p> <p>Formally, if <em>a</em>, <em>b</em>, <em>c</em>, …, <em>y</em>, <em>z</em> are expressions and <em>op1</em>, <em>op2</em>, …, <em>opN</em> are comparison operators, then <code>a op1 b op2 c ... y opN z</code> is equivalent to <code>a op1 b and b op2 c and ... y opN z</code>, except that each expression is evaluated at most once.</p> <p>Note that <code>a op1 b op2 c</code> doesn’t imply any kind of comparison between <em>a</em> and <em>c</em>, so that, e.g., <code>x &lt; y &gt; z</code> is perfectly legal (though perhaps not pretty).</p> <section id="value-comparisons"> <span id="expressions-value-comparisons"></span><h3>
<span class="section-number">6.10.1. </span>Value comparisons</h3> <p>The operators <code>&lt;</code>, <code>&gt;</code>, <code>==</code>, <code>&gt;=</code>, <code>&lt;=</code>, and <code>!=</code> compare the values of two objects. The objects do not need to have the same type.</p> <p>Chapter <a class="reference internal" href="datamodel#objects"><span class="std std-ref">Objects, values and types</span></a> 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.</p> <p>Because all types are (direct or indirect) subtypes of <a class="reference internal" href="../library/functions#object" title="object"><code>object</code></a>, they inherit the default comparison behavior from <a class="reference internal" href="../library/functions#object" title="object"><code>object</code></a>. Types can customize their comparison behavior by implementing <em class="dfn">rich comparison methods</em> like <code>__lt__()</code>, described in <a class="reference internal" href="datamodel#customization"><span class="std std-ref">Basic customization</span></a>.</p> <p>The default behavior for equality comparison (<code>==</code> and <code>!=</code>) 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. <code>x is y</code> implies <code>x == y</code>).</p> <p>A default order comparison (<code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>, and <code>&gt;=</code>) is not provided; an attempt raises <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a>. A motivation for this default behavior is the lack of a similar invariant as for equality.</p> <p>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.</p> <p>The following list describes the comparison behavior of the most important built-in types.</p> <ul> <li>
<p>Numbers of built-in numeric types (<a class="reference internal" href="../library/stdtypes#typesnumeric"><span class="std std-ref">Numeric Types — int, float, complex</span></a>) and of the standard library types <a class="reference internal" href="../library/fractions#fractions.Fraction" title="fractions.Fraction"><code>fractions.Fraction</code></a> and <a class="reference internal" href="../library/decimal#decimal.Decimal" title="decimal.Decimal"><code>decimal.Decimal</code></a> can be compared within and across their types, with the restriction that complex numbers do not support order comparison. Within the limits of the types involved, they compare mathematically (algorithmically) correct without loss of precision.</p> <p>The not-a-number values <code>float('NaN')</code> and <code>decimal.Decimal('NaN')</code> are special. Any ordered comparison of a number to a not-a-number value is false. A counter-intuitive implication is that not-a-number values are not equal to themselves. For example, if <code>x = float('NaN')</code>, <code>3 &lt; x</code>, <code>x &lt; 3</code> and <code>x == x</code> are all false, while <code>x != x</code> is true. This behavior is compliant with IEEE 754.</p> </li> <li>
<code>None</code> and <code>NotImplemented</code> are singletons. <span class="target" id="index-79"></span><a class="pep reference external" href="https://peps.python.org/pep-0008/"><strong>PEP 8</strong></a> advises that comparisons for singletons should always be done with <code>is</code> or <code>is not</code>, never the equality operators.</li> <li>Binary sequences (instances of <a class="reference internal" href="../library/stdtypes#bytes" title="bytes"><code>bytes</code></a> or <a class="reference internal" href="../library/stdtypes#bytearray" title="bytearray"><code>bytearray</code></a>) can be compared within and across their types. They compare lexicographically using the numeric values of their elements.</li> <li>
<p>Strings (instances of <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str</code></a>) compare lexicographically using the numerical Unicode code points (the result of the built-in function <a class="reference internal" href="../library/functions#ord" title="ord"><code>ord()</code></a>) of their characters. <a class="footnote-reference brackets" href="#id19" id="id12">3</a></p> <p>Strings and binary sequences cannot be directly compared.</p> </li> <li>
<p>Sequences (instances of <a class="reference internal" href="../library/stdtypes#tuple" title="tuple"><code>tuple</code></a>, <a class="reference internal" href="../library/stdtypes#list" title="list"><code>list</code></a>, or <a class="reference internal" href="../library/stdtypes#range" title="range"><code>range</code></a>) can be compared only within each of their types, with the restriction that ranges do not support order comparison. Equality comparison across these types results in inequality, and ordering comparison across these types raises <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a>.</p> <p>Sequences compare lexicographically using comparison of corresponding elements. The built-in containers typically assume identical objects are equal to themselves. That lets them bypass equality tests for identical objects to improve performance and to maintain their internal invariants.</p> <p>Lexicographical comparison between built-in collections works as follows:</p> <ul class="simple"> <li>For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, <code>[1,2] == (1,2)</code> is false because the type is not the same).</li> <li>Collections that support order comparison are ordered the same as their first unequal elements (for example, <code>[1,2,x] &lt;= [1,2,y]</code> has the same value as <code>x &lt;= y</code>). If a corresponding element does not exist, the shorter collection is ordered first (for example, <code>[1,2] &lt; [1,2,3]</code> is true).</li> </ul> </li> <li>
<p>Mappings (instances of <a class="reference internal" href="../library/stdtypes#dict" title="dict"><code>dict</code></a>) compare equal if and only if they have equal <code>(key, value)</code> pairs. Equality comparison of the keys and values enforces reflexivity.</p> <p>Order comparisons (<code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>, and <code>&gt;=</code>) raise <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a>.</p> </li> <li>
<p>Sets (instances of <a class="reference internal" href="../library/stdtypes#set" title="set"><code>set</code></a> or <a class="reference internal" href="../library/stdtypes#frozenset" title="frozenset"><code>frozenset</code></a>) can be compared within and across their types.</p> <p>They define order comparison operators to mean subset and superset tests. Those relations do not define total orderings (for example, the two sets <code>{1,2}</code> and <code>{2,3}</code> are not equal, nor subsets of one another, nor supersets of one another). Accordingly, sets are not appropriate arguments for functions which depend on total ordering (for example, <a class="reference internal" href="../library/functions#min" title="min"><code>min()</code></a>, <a class="reference internal" href="../library/functions#max" title="max"><code>max()</code></a>, and <a class="reference internal" href="../library/functions#sorted" title="sorted"><code>sorted()</code></a> produce undefined results given a list of sets as inputs).</p> <p>Comparison of sets enforces reflexivity of its elements.</p> </li> <li>Most other built-in types have no comparison methods implemented, so they inherit the default comparison behavior.</li> </ul> <p>User-defined classes that customize their comparison behavior should follow some consistency rules, if possible:</p> <ul> <li>
<p>Equality comparison should be reflexive. In other words, identical objects should compare equal:</p>  <p><code>x is y</code> implies <code>x == y</code></p>  </li> <li>
<p>Comparison should be symmetric. In other words, the following expressions should have the same result:</p>  <p><code>x == y</code> and <code>y == x</code></p> <p><code>x != y</code> and <code>y != x</code></p> <p><code>x &lt; y</code> and <code>y &gt; x</code></p> <p><code>x &lt;= y</code> and <code>y &gt;= x</code></p>  </li> <li>
<p>Comparison should be transitive. The following (non-exhaustive) examples illustrate that:</p>  <p><code>x &gt; y and y &gt; z</code> implies <code>x &gt; z</code></p> <p><code>x &lt; y and y &lt;= z</code> implies <code>x &lt; z</code></p>  </li> <li>
<p>Inverse comparison should result in the boolean negation. In other words, the following expressions should have the same result:</p>  <p><code>x == y</code> and <code>not x != y</code></p> <p><code>x &lt; y</code> and <code>not x &gt;= y</code> (for total ordering)</p> <p><code>x &gt; y</code> and <code>not x &lt;= y</code> (for total ordering)</p>  <p>The last two expressions apply to totally ordered collections (e.g. to sequences, but not to sets or mappings). See also the <a class="reference internal" href="../library/functools#functools.total_ordering" title="functools.total_ordering"><code>total_ordering()</code></a> decorator.</p> </li> <li>The <a class="reference internal" href="../library/functions#hash" title="hash"><code>hash()</code></a> result should be consistent with equality. Objects that are equal should either have the same hash value, or be marked as unhashable.</li> </ul> <p>Python does not enforce these consistency rules. In fact, the not-a-number values are an example for not following these rules.</p> </section> <section id="membership-test-operations"> <span id="membership-test-details"></span><span id="not-in"></span><span id="in"></span><h3>
<span class="section-number">6.10.2. </span>Membership test operations</h3> <p>The operators <a class="reference internal" href="#in"><code>in</code></a> and <a class="reference internal" href="#not-in"><code>not in</code></a> test for membership. <code>x in
s</code> evaluates to <code>True</code> if <em>x</em> is a member of <em>s</em>, and <code>False</code> otherwise. <code>x not in s</code> returns the negation of <code>x in s</code>. All built-in sequences and set types support this as well as dictionary, for which <code>in</code> tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression <code>x in y</code> is equivalent to <code>any(x is e or x == e for e in y)</code>.</p> <p>For the string and bytes types, <code>x in y</code> is <code>True</code> if and only if <em>x</em> is a substring of <em>y</em>. An equivalent test is <code>y.find(x) != -1</code>. Empty strings are always considered to be a substring of any other string, so <code>"" in "abc"</code> will return <code>True</code>.</p> <p>For user-defined classes which define the <code>__contains__()</code> method, <code>x in
y</code> returns <code>True</code> if <code>y.__contains__(x)</code> returns a true value, and <code>False</code> otherwise.</p> <p>For user-defined classes which do not define <code>__contains__()</code> but do define <code>__iter__()</code>, <code>x in y</code> is <code>True</code> if some value <code>z</code>, for which the expression <code>x is z or x == z</code> is true, is produced while iterating over <code>y</code>. If an exception is raised during the iteration, it is as if <a class="reference internal" href="#in"><code>in</code></a> raised that exception.</p> <p>Lastly, the old-style iteration protocol is tried: if a class defines <a class="reference internal" href="datamodel#object.__getitem__" title="object.__getitem__"><code>__getitem__()</code></a>, <code>x in y</code> is <code>True</code> if and only if there is a non-negative integer index <em>i</em> such that <code>x is y[i] or x == y[i]</code>, and no lower integer index raises the <a class="reference internal" href="../library/exceptions#IndexError" title="IndexError"><code>IndexError</code></a> exception. (If any other exception is raised, it is as if <a class="reference internal" href="#in"><code>in</code></a> raised that exception).</p> <p id="index-80">The operator <a class="reference internal" href="#not-in"><code>not in</code></a> is defined to have the inverse truth value of <a class="reference internal" href="#in"><code>in</code></a>.</p> </section> <section id="is-not"> <span id="is"></span><span id="index-81"></span><span id="identity-comparisons"></span><h3>
<span class="section-number">6.10.3. </span>Identity comparisons</h3> <p>The operators <a class="reference internal" href="#is"><code>is</code></a> and <a class="reference internal" href="#is-not"><code>is not</code></a> test for an object’s identity: <code>x
is y</code> is true if and only if <em>x</em> and <em>y</em> are the same object. An Object’s identity is determined using the <a class="reference internal" href="../library/functions#id" title="id"><code>id()</code></a> function. <code>x is not y</code> yields the inverse truth value. <a class="footnote-reference brackets" href="#id20" id="id13">4</a></p> </section> </section> <section id="boolean-operations"> <span id="not"></span><span id="or"></span><span id="and"></span><span id="booleans"></span><h2>
<span class="section-number">6.11. </span>Boolean operations</h2> <pre id="index-82">
<strong id="grammar-token-python-grammar-or_test"><span id="grammar-token-or-test"></span>or_test </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-and_test">and_test</a> | <a class="reference internal" href="#grammar-token-python-grammar-or_test">or_test</a> "or" <a class="reference internal" href="#grammar-token-python-grammar-and_test">and_test</a>
<strong id="grammar-token-python-grammar-and_test"><span id="grammar-token-and-test"></span>and_test</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-not_test">not_test</a> | <a class="reference internal" href="#grammar-token-python-grammar-and_test">and_test</a> "and" <a class="reference internal" href="#grammar-token-python-grammar-not_test">not_test</a>
<strong id="grammar-token-python-grammar-not_test"><span id="grammar-token-not-test"></span>not_test</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-comparison">comparison</a> | "not" <a class="reference internal" href="#grammar-token-python-grammar-not_test">not_test</a>
</pre> <p>In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: <code>False</code>, <code>None</code>, 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 <a class="reference internal" href="datamodel#object.__bool__" title="object.__bool__"><code>__bool__()</code></a> method.</p> <p id="index-83">The operator <a class="reference internal" href="#not"><code>not</code></a> yields <code>True</code> if its argument is false, <code>False</code> otherwise.</p> <p id="index-84">The expression <code>x and y</code> first evaluates <em>x</em>; if <em>x</em> is false, its value is returned; otherwise, <em>y</em> is evaluated and the resulting value is returned.</p> <p id="index-85">The expression <code>x or y</code> first evaluates <em>x</em>; if <em>x</em> is true, its value is returned; otherwise, <em>y</em> is evaluated and the resulting value is returned.</p> <p>Note that neither <a class="reference internal" href="#and"><code>and</code></a> nor <a class="reference internal" href="#or"><code>or</code></a> restrict the value and type they return to <code>False</code> and <code>True</code>, but rather return the last evaluated argument. This is sometimes useful, e.g., if <code>s</code> is a string that should be replaced by a default value if it is empty, the expression <code>s or 'foo'</code> yields the desired value. Because <a class="reference internal" href="#not"><code>not</code></a> has to create a new value, it returns a boolean value regardless of the type of its argument (for example, <code>not 'foo'</code> produces <code>False</code> rather than <code>''</code>.)</p> </section> <section id="assignment-expressions"> <span id="index-86"></span><h2>
<span class="section-number">6.12. </span>Assignment expressions</h2> <pre>
<strong id="grammar-token-python-grammar-assignment_expression"><span id="grammar-token-assignment-expression"></span>assignment_expression</strong> ::=  [<a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-identifier">identifier</a> ":="] <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a>
</pre> <p>An assignment expression (sometimes also called a “named expression” or “walrus”) assigns an <a class="reference internal" href="#grammar-token-python-grammar-expression"><code>expression</code></a> to an <a class="reference internal" href="lexical_analysis#grammar-token-python-grammar-identifier"><code>identifier</code></a>, while also returning the value of the <a class="reference internal" href="#grammar-token-python-grammar-expression"><code>expression</code></a>.</p> <p>One common use case is when handling matched regular expressions:</p> <pre data-language="python">if matching := pattern.search(data):
    do_something(matching)
</pre> <p>Or, when processing a file stream in chunks:</p> <pre data-language="python">while chunk := file.read(9000):
    process(chunk)
</pre> <p>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 <code>assert</code>, <code>with</code>, and <code>assignment</code> statements. In all other places where they can be used, parentheses are not required, including in <code>if</code> and <code>while</code> statements.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8: </span>See <span class="target" id="index-87"></span><a class="pep reference external" href="https://peps.python.org/pep-0572/"><strong>PEP 572</strong></a> for more details about assignment expressions.</p> </div> </section> <section id="conditional-expressions"> <span id="if-expr"></span><h2>
<span class="section-number">6.13. </span>Conditional expressions</h2> <pre id="index-88">
<strong id="grammar-token-python-grammar-conditional_expression"><span id="grammar-token-conditional-expression"></span>conditional_expression</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-or_test">or_test</a> ["if" <a class="reference internal" href="#grammar-token-python-grammar-or_test">or_test</a> "else" <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a>]
<strong id="grammar-token-python-grammar-expression"><span id="grammar-token-expression"></span>expression            </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-conditional_expression">conditional_expression</a> | <a class="reference internal" href="#grammar-token-python-grammar-lambda_expr">lambda_expr</a>
</pre> <p>Conditional expressions (sometimes called a “ternary operator”) have the lowest priority of all Python operations.</p> <p>The expression <code>x if C else y</code> first evaluates the condition, <em>C</em> rather than <em>x</em>. If <em>C</em> is true, <em>x</em> is evaluated and its value is returned; otherwise, <em>y</em> is evaluated and its value is returned.</p> <p>See <span class="target" id="index-89"></span><a class="pep reference external" href="https://peps.python.org/pep-0308/"><strong>PEP 308</strong></a> for more details about conditional expressions.</p> </section> <section id="lambda"> <span id="lambdas"></span><span id="id14"></span><h2>
<span class="section-number">6.14. </span>Lambdas</h2> <pre id="index-90">
<strong id="grammar-token-python-grammar-lambda_expr"><span id="grammar-token-lambda-expr"></span>lambda_expr</strong> ::=  "lambda" [<a class="reference internal" href="compound_stmts#grammar-token-python-grammar-parameter_list">parameter_list</a>] ":" <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a>
</pre> <p>Lambda expressions (sometimes called lambda forms) are used to create anonymous functions. The expression <code>lambda parameters: expression</code> yields a function object. The unnamed object behaves like a function object defined with:</p> <pre data-language="none">def &lt;lambda&gt;(parameters):
    return expression
</pre> <p>See section <a class="reference internal" href="compound_stmts#function"><span class="std std-ref">Function definitions</span></a> for the syntax of parameter lists. Note that functions created with lambda expressions cannot contain statements or annotations.</p> </section> <section id="expression-lists"> <span id="exprlists"></span><h2>
<span class="section-number">6.15. </span>Expression lists</h2> <pre id="index-91">
<strong id="grammar-token-python-grammar-expression_list"><span id="grammar-token-expression-list"></span>expression_list   </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a> ("," <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a>)* [","]
<strong id="grammar-token-python-grammar-starred_list"><span id="grammar-token-starred-list"></span>starred_list      </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-starred_item">starred_item</a> ("," <a class="reference internal" href="#grammar-token-python-grammar-starred_item">starred_item</a>)* [","]
<strong id="grammar-token-python-grammar-starred_expression"><span id="grammar-token-starred-expression"></span>starred_expression</strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-expression">expression</a> | (<a class="reference internal" href="#grammar-token-python-grammar-starred_item">starred_item</a> ",")* [<a class="reference internal" href="#grammar-token-python-grammar-starred_item">starred_item</a>]
<strong id="grammar-token-python-grammar-starred_item"><span id="grammar-token-starred-item"></span>starred_item      </strong> ::=  <a class="reference internal" href="#grammar-token-python-grammar-assignment_expression">assignment_expression</a> | "*" <a class="reference internal" href="#grammar-token-python-grammar-or_expr">or_expr</a>
</pre> <p id="index-92">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.</p> <p id="index-93">An asterisk <code>*</code> denotes <em class="dfn">iterable unpacking</em>. Its operand must be an <a class="reference internal" href="../glossary#term-iterable"><span class="xref std std-term">iterable</span></a>. 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.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.5: </span>Iterable unpacking in expression lists, originally proposed by <span class="target" id="index-94"></span><a class="pep reference external" href="https://peps.python.org/pep-0448/"><strong>PEP 448</strong></a>.</p> </div> <p id="index-95">The trailing comma is required only to create a single tuple (a.k.a. a <em>singleton</em>); 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: <code>()</code>.)</p> </section> <section id="evaluation-order"> <span id="evalorder"></span><h2>
<span class="section-number">6.16. </span>Evaluation order</h2> <p id="index-96">Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.</p> <p>In the following lines, expressions will be evaluated in the arithmetic order of their suffixes:</p> <pre data-language="python">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
</pre> </section> <section id="operator-precedence"> <span id="operator-summary"></span><h2>
<span class="section-number">6.17. </span>Operator precedence</h2> <p id="index-97">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).</p> <p>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 <a class="reference internal" href="#comparisons"><span class="std std-ref">Comparisons</span></a> section.</p> <table class="docutils align-default">  <thead> <tr>
<th class="head"><p>Operator</p></th> <th class="head"><p>Description</p></th> </tr> </thead>  <tr>
<td>
<p><code>(expressions...)</code>,</p> <p><code>[expressions...]</code>, <code>{key: value...}</code>, <code>{expressions...}</code></p> </td> <td><p>Binding or parenthesized expression, list display, dictionary display, set display</p></td> </tr> <tr>
<td><p><code>x[index]</code>, <code>x[index:index]</code>, <code>x(arguments...)</code>, <code>x.attribute</code></p></td> <td><p>Subscription, slicing, call, attribute reference</p></td> </tr> <tr>
<td><p><a class="reference internal" href="#await"><code>await x</code></a></p></td> <td><p>Await expression</p></td> </tr> <tr>
<td><p><code>**</code></p></td> <td><p>Exponentiation <a class="footnote-reference brackets" href="#id21" id="id15">5</a></p></td> </tr> <tr>
<td><p><code>+x</code>, <code>-x</code>, <code>~x</code></p></td> <td><p>Positive, negative, bitwise NOT</p></td> </tr> <tr>
<td><p><code>*</code>, <code>@</code>, <code>/</code>, <code>//</code>, <code>%</code></p></td> <td><p>Multiplication, matrix multiplication, division, floor division, remainder <a class="footnote-reference brackets" href="#id22" id="id16">6</a></p></td> </tr> <tr>
<td><p><code>+</code>, <code>-</code></p></td> <td><p>Addition and subtraction</p></td> </tr> <tr>
<td><p><code>&lt;&lt;</code>, <code>&gt;&gt;</code></p></td> <td><p>Shifts</p></td> </tr> <tr>
<td><p><code>&amp;</code></p></td> <td><p>Bitwise AND</p></td> </tr> <tr>
<td><p><code>^</code></p></td> <td><p>Bitwise XOR</p></td> </tr> <tr>
<td><p><code>|</code></p></td> <td><p>Bitwise OR</p></td> </tr> <tr>
<td><p><a class="reference internal" href="#in"><code>in</code></a>, <a class="reference internal" href="#not-in"><code>not in</code></a>, <a class="reference internal" href="#is"><code>is</code></a>, <a class="reference internal" href="#is-not"><code>is not</code></a>, <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, <code>&gt;=</code>, <code>!=</code>, <code>==</code></p></td> <td><p>Comparisons, including membership tests and identity tests</p></td> </tr> <tr>
<td><p><a class="reference internal" href="#not"><code>not x</code></a></p></td> <td><p>Boolean NOT</p></td> </tr> <tr>
<td><p><a class="reference internal" href="#and"><code>and</code></a></p></td> <td><p>Boolean AND</p></td> </tr> <tr>
<td><p><a class="reference internal" href="#or"><code>or</code></a></p></td> <td><p>Boolean OR</p></td> </tr> <tr>
<td><p><a class="reference internal" href="#if-expr"><code>if</code></a> – <code>else</code></p></td> <td><p>Conditional expression</p></td> </tr> <tr>
<td><p><a class="reference internal" href="#lambda"><code>lambda</code></a></p></td> <td><p>Lambda expression</p></td> </tr> <tr>
<td><p><code>:=</code></p></td> <td><p>Assignment expression</p></td> </tr>  </table> <h4 class="rubric">Footnotes</h4> <dl class="footnote brackets"> <dt class="label" id="id17">
<code>1</code> </dt> <dd>
<p>While <code>abs(x%y) &lt; abs(y)</code> 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 <code>-1e-100 %
1e100</code> have the same sign as <code>1e100</code>, the computed result is <code>-1e-100 +
1e100</code>, which is numerically exactly equal to <code>1e100</code>. The function <a class="reference internal" href="../library/math#math.fmod" title="math.fmod"><code>math.fmod()</code></a> returns a result whose sign matches the sign of the first argument instead, and so returns <code>-1e-100</code> in this case. Which approach is more appropriate depends on the application.</p> </dd> <dt class="label" id="id18">
<code>2</code> </dt> <dd>
<p>If x is very close to an exact integer multiple of y, it’s possible for <code>x//y</code> to be one larger than <code>(x-x%y)//y</code> due to rounding. In such cases, Python returns the latter result, in order to preserve that <code>divmod(x,y)[0] * y + x % y</code> be very close to <code>x</code>.</p> </dd> <dt class="label" id="id19">
<code>3</code> </dt> <dd>
<p>The Unicode standard distinguishes between <em class="dfn">code points</em> (e.g. U+0041) and <em class="dfn">abstract characters</em> (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 <em class="dfn">precomposed character</em> at code position U+00C7, or as a sequence of a <em class="dfn">base character</em> at code position U+0043 (LATIN CAPITAL LETTER C), followed by a <em class="dfn">combining character</em> at code position U+0327 (COMBINING CEDILLA).</p> <p>The comparison operators on strings compare at the level of Unicode code points. This may be counter-intuitive to humans. For example, <code>"\u00C7" == "\u0043\u0327"</code> is <code>False</code>, even though both strings represent the same abstract character “LATIN CAPITAL LETTER C WITH CEDILLA”.</p> <p>To compare strings at the level of abstract characters (that is, in a way intuitive to humans), use <a class="reference internal" href="../library/unicodedata#unicodedata.normalize" title="unicodedata.normalize"><code>unicodedata.normalize()</code></a>.</p> </dd> <dt class="label" id="id20">
<code>4</code> </dt> <dd>
<p>Due to automatic garbage-collection, free lists, and the dynamic nature of descriptors, you may notice seemingly unusual behaviour in certain uses of the <a class="reference internal" href="#is"><code>is</code></a> operator, like those involving comparisons between instance methods, or constants. Check their documentation for more info.</p> </dd> <dt class="label" id="id21">
<code>5</code> </dt> <dd>
<p>The power operator <code>**</code> binds less tightly than an arithmetic or bitwise unary operator on its right, that is, <code>2**-1</code> is <code>0.5</code>.</p> </dd> <dt class="label" id="id22">
<code>6</code> </dt> <dd>
<p>The <code>%</code> operator is also used for string formatting; the same precedence applies.</p> </dd> </dl> </section> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/reference/expressions.html" class="_attribution-link">https://docs.python.org/3.12/reference/expressions.html</a>
  </p>
</div>