blob: 97461627bfd0343771ed259e522c0e228cedf59d [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2.. _expressions:
3
4***********
5Expressions
6***********
7
Georg Brandl4b491312007-08-31 09:22:56 +00008.. index:: expression, BNF
Georg Brandl116aa622007-08-15 14:28:22 +00009
Brett Cannon7603fa02011-01-06 23:08:16 +000010This chapter explains the meaning of the elements of expressions in Python.
Georg Brandl116aa622007-08-15 14:28:22 +000011
Georg Brandl116aa622007-08-15 14:28:22 +000012**Syntax Notes:** In this and the following chapters, extended BNF notation will
13be used to describe syntax, not lexical analysis. When (one alternative of) a
14syntax rule has the form
15
16.. productionlist:: *
17 name: `othername`
18
Georg Brandl116aa622007-08-15 14:28:22 +000019and no semantics are given, the semantics of this form of ``name`` are the same
20as for ``othername``.
21
22
23.. _conversions:
24
25Arithmetic conversions
26======================
27
28.. index:: pair: arithmetic; conversion
29
Georg Brandl116aa622007-08-15 14:28:22 +000030When a description of an arithmetic operator below uses the phrase "the numeric
Georg Brandl96593ed2007-09-07 14:15:41 +000031arguments are converted to a common type," this means that the operator
32implementation for built-in types works that way:
Georg Brandl116aa622007-08-15 14:28:22 +000033
34* If either argument is a complex number, the other is converted to complex;
35
36* otherwise, if either argument is a floating point number, the other is
37 converted to floating point;
38
Georg Brandl96593ed2007-09-07 14:15:41 +000039* otherwise, both must be integers and no conversion is necessary.
Georg Brandl116aa622007-08-15 14:28:22 +000040
41Some additional rules apply for certain operators (e.g., a string left argument
Georg Brandl96593ed2007-09-07 14:15:41 +000042to the '%' operator). Extensions must define their own conversion behavior.
Georg Brandl116aa622007-08-15 14:28:22 +000043
44
45.. _atoms:
46
47Atoms
48=====
49
Georg Brandl96593ed2007-09-07 14:15:41 +000050.. index:: atom
Georg Brandl116aa622007-08-15 14:28:22 +000051
52Atoms are the most basic elements of expressions. The simplest atoms are
Georg Brandl96593ed2007-09-07 14:15:41 +000053identifiers or literals. Forms enclosed in parentheses, brackets or braces are
54also categorized syntactically as atoms. The syntax for atoms is:
Georg Brandl116aa622007-08-15 14:28:22 +000055
56.. productionlist::
57 atom: `identifier` | `literal` | `enclosure`
Georg Brandl96593ed2007-09-07 14:15:41 +000058 enclosure: `parenth_form` | `list_display` | `dict_display` | `set_display`
59 : | `generator_expression` | `yield_atom`
Georg Brandl116aa622007-08-15 14:28:22 +000060
61
62.. _atom-identifiers:
63
64Identifiers (Names)
65-------------------
66
Georg Brandl96593ed2007-09-07 14:15:41 +000067.. index:: name, identifier
Georg Brandl116aa622007-08-15 14:28:22 +000068
69An identifier occurring as an atom is a name. See section :ref:`identifiers`
70for lexical definition and section :ref:`naming` for documentation of naming and
71binding.
72
73.. index:: exception: NameError
74
75When the name is bound to an object, evaluation of the atom yields that object.
76When a name is not bound, an attempt to evaluate it raises a :exc:`NameError`
77exception.
78
79.. index::
80 pair: name; mangling
81 pair: private; names
82
83**Private name mangling:** When an identifier that textually occurs in a class
84definition begins with two or more underscore characters and does not end in two
85or more underscores, it is considered a :dfn:`private name` of that class.
86Private names are transformed to a longer form before code is generated for
87them. The transformation inserts the class name in front of the name, with
88leading underscores removed, and a single underscore inserted in front of the
89class name. For example, the identifier ``__spam`` occurring in a class named
90``Ham`` will be transformed to ``_Ham__spam``. This transformation is
91independent of the syntactical context in which the identifier is used. If the
92transformed name is extremely long (longer than 255 characters), implementation
93defined truncation may happen. If the class name consists only of underscores,
94no transformation is done.
95
Georg Brandl116aa622007-08-15 14:28:22 +000096
97.. _atom-literals:
98
99Literals
100--------
101
102.. index:: single: literal
103
Georg Brandl96593ed2007-09-07 14:15:41 +0000104Python supports string and bytes literals and various numeric literals:
Georg Brandl116aa622007-08-15 14:28:22 +0000105
106.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000107 literal: `stringliteral` | `bytesliteral`
108 : | `integer` | `floatnumber` | `imagnumber`
Georg Brandl116aa622007-08-15 14:28:22 +0000109
Georg Brandl96593ed2007-09-07 14:15:41 +0000110Evaluation of a literal yields an object of the given type (string, bytes,
111integer, floating point number, complex number) with the given value. The value
112may be approximated in the case of floating point and imaginary (complex)
Georg Brandl116aa622007-08-15 14:28:22 +0000113literals. See section :ref:`literals` for details.
114
115.. index::
116 triple: immutable; data; type
117 pair: immutable; object
118
Georg Brandl96593ed2007-09-07 14:15:41 +0000119With the exception of bytes literals, these all correspond to immutable data
120types, and hence the object's identity is less important than its value.
121Multiple evaluations of literals with the same value (either the same occurrence
122in the program text or a different occurrence) may obtain the same object or a
123different object with the same value.
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125
126.. _parenthesized:
127
128Parenthesized forms
129-------------------
130
131.. index:: single: parenthesized form
132
133A parenthesized form is an optional expression list enclosed in parentheses:
134
135.. productionlist::
136 parenth_form: "(" [`expression_list`] ")"
137
138A parenthesized expression list yields whatever that expression list yields: if
139the list contains at least one comma, it yields a tuple; otherwise, it yields
140the single expression that makes up the expression list.
141
142.. index:: pair: empty; tuple
143
144An empty pair of parentheses yields an empty tuple object. Since tuples are
145immutable, the rules for literals apply (i.e., two occurrences of the empty
146tuple may or may not yield the same object).
147
148.. index::
149 single: comma
150 pair: tuple; display
151
152Note that tuples are not formed by the parentheses, but rather by use of the
153comma operator. The exception is the empty tuple, for which parentheses *are*
154required --- allowing unparenthesized "nothing" in expressions would cause
155ambiguities and allow common typos to pass uncaught.
156
157
Georg Brandl96593ed2007-09-07 14:15:41 +0000158.. _comprehensions:
159
160Displays for lists, sets and dictionaries
161-----------------------------------------
162
163For constructing a list, a set or a dictionary Python provides special syntax
164called "displays", each of them in two flavors:
165
166* either the container contents are listed explicitly, or
167
168* they are computed via a set of looping and filtering instructions, called a
169 :dfn:`comprehension`.
170
171Common syntax elements for comprehensions are:
172
173.. productionlist::
174 comprehension: `expression` `comp_for`
175 comp_for: "for" `target_list` "in" `or_test` [`comp_iter`]
176 comp_iter: `comp_for` | `comp_if`
177 comp_if: "if" `expression_nocond` [`comp_iter`]
178
179The comprehension consists of a single expression followed by at least one
180:keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if` clauses.
181In this case, the elements of the new container are those that would be produced
182by considering each of the :keyword:`for` or :keyword:`if` clauses a block,
183nesting from left to right, and evaluating the expression to produce an element
184each time the innermost block is reached.
185
Georg Brandl02c30562007-09-07 17:52:53 +0000186Note that the comprehension is executed in a separate scope, so names assigned
187to in the target list don't "leak" in the enclosing scope.
188
Georg Brandl96593ed2007-09-07 14:15:41 +0000189
Georg Brandl116aa622007-08-15 14:28:22 +0000190.. _lists:
191
192List displays
193-------------
194
195.. index::
196 pair: list; display
197 pair: list; comprehensions
Georg Brandl96593ed2007-09-07 14:15:41 +0000198 pair: empty; list
199 object: list
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201A list display is a possibly empty series of expressions enclosed in square
202brackets:
203
204.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000205 list_display: "[" [`expression_list` | `comprehension`] "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000206
Georg Brandl96593ed2007-09-07 14:15:41 +0000207A list display yields a new list object, the contents being specified by either
208a list of expressions or a comprehension. When a comma-separated list of
209expressions is supplied, its elements are evaluated from left to right and
210placed into the list object in that order. When a comprehension is supplied,
211the list is constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000212
213
Georg Brandl96593ed2007-09-07 14:15:41 +0000214.. _set:
Georg Brandl116aa622007-08-15 14:28:22 +0000215
Georg Brandl96593ed2007-09-07 14:15:41 +0000216Set displays
217------------
Georg Brandl116aa622007-08-15 14:28:22 +0000218
Georg Brandl96593ed2007-09-07 14:15:41 +0000219.. index:: pair: set; display
220 object: set
Georg Brandl116aa622007-08-15 14:28:22 +0000221
Georg Brandl96593ed2007-09-07 14:15:41 +0000222A set display is denoted by curly braces and distinguishable from dictionary
223displays by the lack of colons separating keys and values:
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225.. productionlist::
Georg Brandl528cdb12008-09-21 07:09:51 +0000226 set_display: "{" (`expression_list` | `comprehension`) "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000227
Georg Brandl96593ed2007-09-07 14:15:41 +0000228A set display yields a new mutable set object, the contents being specified by
229either a sequence of expressions or a comprehension. When a comma-separated
230list of expressions is supplied, its elements are evaluated from left to right
231and added to the set object. When a comprehension is supplied, the set is
232constructed from the elements resulting from the comprehension.
Georg Brandl116aa622007-08-15 14:28:22 +0000233
Georg Brandl528cdb12008-09-21 07:09:51 +0000234An empty set cannot be constructed with ``{}``; this literal constructs an empty
235dictionary.
Christian Heimes78644762008-03-04 23:39:23 +0000236
237
Georg Brandl116aa622007-08-15 14:28:22 +0000238.. _dict:
239
240Dictionary displays
241-------------------
242
243.. index:: pair: dictionary; display
Georg Brandl96593ed2007-09-07 14:15:41 +0000244 key, datum, key/datum pair
245 object: dictionary
Georg Brandl116aa622007-08-15 14:28:22 +0000246
247A dictionary display is a possibly empty series of key/datum pairs enclosed in
248curly braces:
249
250.. productionlist::
Georg Brandl96593ed2007-09-07 14:15:41 +0000251 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
Georg Brandl116aa622007-08-15 14:28:22 +0000252 key_datum_list: `key_datum` ("," `key_datum`)* [","]
253 key_datum: `expression` ":" `expression`
Georg Brandl96593ed2007-09-07 14:15:41 +0000254 dict_comprehension: `expression` ":" `expression` `comp_for`
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256A dictionary display yields a new dictionary object.
257
Georg Brandl96593ed2007-09-07 14:15:41 +0000258If a comma-separated sequence of key/datum pairs is given, they are evaluated
259from left to right to define the entries of the dictionary: each key object is
260used as a key into the dictionary to store the corresponding datum. This means
261that you can specify the same key multiple times in the key/datum list, and the
262final dictionary's value for that key will be the last one given.
263
264A dict comprehension, in contrast to list and set comprehensions, needs two
265expressions separated with a colon followed by the usual "for" and "if" clauses.
266When the comprehension is run, the resulting key and value elements are inserted
267in the new dictionary in the order they are produced.
Georg Brandl116aa622007-08-15 14:28:22 +0000268
269.. index:: pair: immutable; object
Georg Brandl96593ed2007-09-07 14:15:41 +0000270 hashable
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272Restrictions on the types of the key values are listed earlier in section
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000273:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl116aa622007-08-15 14:28:22 +0000274all mutable objects.) Clashes between duplicate keys are not detected; the last
275datum (textually rightmost in the display) stored for a given key value
276prevails.
277
278
Georg Brandl96593ed2007-09-07 14:15:41 +0000279.. _genexpr:
280
281Generator expressions
282---------------------
283
284.. index:: pair: generator; expression
285 object: generator
286
287A generator expression is a compact generator notation in parentheses:
288
289.. productionlist::
290 generator_expression: "(" `expression` `comp_for` ")"
291
292A generator expression yields a new generator object. Its syntax is the same as
293for comprehensions, except that it is enclosed in parentheses instead of
294brackets or curly braces.
295
296Variables used in the generator expression are evaluated lazily when the
297:meth:`__next__` method is called for generator object (in the same fashion as
298normal generators). However, the leftmost :keyword:`for` clause is immediately
299evaluated, so that an error produced by it can be seen before any other possible
300error in the code that handles the generator expression. Subsequent
301:keyword:`for` clauses cannot be evaluated immediately since they may depend on
302the previous :keyword:`for` loop. For example: ``(x*y for x in range(10) for y
303in bar(x))``.
304
305The parentheses can be omitted on calls with only one argument. See section
306:ref:`calls` for the detail.
307
308
Georg Brandl116aa622007-08-15 14:28:22 +0000309.. _yieldexpr:
310
311Yield expressions
312-----------------
313
314.. index::
315 keyword: yield
316 pair: yield; expression
317 pair: generator; function
318
319.. productionlist::
320 yield_atom: "(" `yield_expression` ")"
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000321 yield_expression: "yield" [`expression_list` | "from" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000322
Georg Brandl116aa622007-08-15 14:28:22 +0000323The :keyword:`yield` expression is only used when defining a generator function,
Georg Brandl96593ed2007-09-07 14:15:41 +0000324and can only be used in the body of a function definition. Using a
Georg Brandl116aa622007-08-15 14:28:22 +0000325:keyword:`yield` expression in a function definition is sufficient to cause that
326definition to create a generator function instead of a normal function.
327
328When a generator function is called, it returns an iterator known as a
329generator. That generator then controls the execution of a generator function.
330The execution starts when one of the generator's methods is called. At that
331time, the execution proceeds to the first :keyword:`yield` expression, where it
332is suspended again, returning the value of :token:`expression_list` to
333generator's caller. By suspended we mean that all local state is retained,
334including the current bindings of local variables, the instruction pointer, and
335the internal evaluation stack. When the execution is resumed by calling one of
336the generator's methods, the function can proceed exactly as if the
Georg Brandl96593ed2007-09-07 14:15:41 +0000337:keyword:`yield` expression was just another external call. The value of the
Georg Brandl116aa622007-08-15 14:28:22 +0000338:keyword:`yield` expression after resuming depends on the method which resumed
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000339the execution. If :meth:`__next__` is used (typically via either a
340:keyword:`for` or the :func:`next` builtin) then the result is :const:`None`,
341otherwise, if :meth:`send` is used, then the result will be the value passed
342in to that method.
Georg Brandl116aa622007-08-15 14:28:22 +0000343
344.. index:: single: coroutine
345
346All of this makes generator functions quite similar to coroutines; they yield
347multiple times, they have more than one entry point and their execution can be
348suspended. The only difference is that a generator function cannot control
349where should the execution continue after it yields; the control is always
Georg Brandl6faee4e2010-09-21 14:48:28 +0000350transferred to the generator's caller.
Georg Brandl116aa622007-08-15 14:28:22 +0000351
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000352:keyword:`yield` expressions are allowed in the :keyword:`try` clause of a
Georg Brandl02c30562007-09-07 17:52:53 +0000353:keyword:`try` ... :keyword:`finally` construct. If the generator is not
354resumed before it is finalized (by reaching a zero reference count or by being
355garbage collected), the generator-iterator's :meth:`close` method will be
356called, allowing any pending :keyword:`finally` clauses to execute.
357
Nick Coghlan0ed80192012-01-14 14:43:24 +1000358When ``yield from <expr>`` is used, it treats the supplied expression as
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000359a subiterator. All values produced by that subiterator are passed directly
360to the caller of the current generator's methods. Any values passed in with
361:meth:`send` and any exceptions passed in with :meth:`throw` are passed to
362the underlying iterator if it has the appropriate methods. If this is not the
363case, then :meth:`send` will raise :exc:`AttributeError` or :exc:`TypeError`,
364while :meth:`throw` will just raise the passed in exception immediately.
365
366When the underlying iterator is complete, the :attr:`~StopIteration.value`
367attribute of the raised :exc:`StopIteration` instance becomes the value of
368the yield expression. It can be either set explicitly when raising
369:exc:`StopIteration`, or automatically when the sub-iterator is a generator
370(by returning a value from the sub-generator).
371
Nick Coghlan0ed80192012-01-14 14:43:24 +1000372 .. versionchanged:: 3.3
373 Added ``yield from <expr>`` to delegate control flow to a subiterator
374
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000375The parentheses can be omitted when the :keyword:`yield` expression is the
376sole expression on the right hand side of an assignment statement.
377
Georg Brandl116aa622007-08-15 14:28:22 +0000378.. index:: object: generator
379
380The following generator's methods can be used to control the execution of a
381generator function:
382
383.. index:: exception: StopIteration
384
385
Georg Brandl96593ed2007-09-07 14:15:41 +0000386.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000387
Georg Brandl96593ed2007-09-07 14:15:41 +0000388 Starts the execution of a generator function or resumes it at the last
389 executed :keyword:`yield` expression. When a generator function is resumed
Benjamin Petersone7c78b22008-07-03 20:28:26 +0000390 with a :meth:`__next__` method, the current :keyword:`yield` expression
391 always evaluates to :const:`None`. The execution then continues to the next
Georg Brandl96593ed2007-09-07 14:15:41 +0000392 :keyword:`yield` expression, where the generator is suspended again, and the
393 value of the :token:`expression_list` is returned to :meth:`next`'s caller.
394 If the generator exits without yielding another value, a :exc:`StopIteration`
395 exception is raised.
396
397 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
398 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000399
400
401.. method:: generator.send(value)
402
403 Resumes the execution and "sends" a value into the generator function. The
404 ``value`` argument becomes the result of the current :keyword:`yield`
405 expression. The :meth:`send` method returns the next value yielded by the
406 generator, or raises :exc:`StopIteration` if the generator exits without
Georg Brandl96593ed2007-09-07 14:15:41 +0000407 yielding another value. When :meth:`send` is called to start the generator,
408 it must be called with :const:`None` as the argument, because there is no
Christian Heimesc3f30c42008-02-22 16:37:40 +0000409 :keyword:`yield` expression that could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000410
411
412.. method:: generator.throw(type[, value[, traceback]])
413
414 Raises an exception of type ``type`` at the point where generator was paused,
415 and returns the next value yielded by the generator function. If the generator
416 exits without yielding another value, a :exc:`StopIteration` exception is
417 raised. If the generator function does not catch the passed-in exception, or
418 raises a different exception, then that exception propagates to the caller.
419
420.. index:: exception: GeneratorExit
421
422
423.. method:: generator.close()
424
425 Raises a :exc:`GeneratorExit` at the point where the generator function was
Georg Brandl96593ed2007-09-07 14:15:41 +0000426 paused. If the generator function then raises :exc:`StopIteration` (by
427 exiting normally, or due to already being closed) or :exc:`GeneratorExit` (by
428 not catching the exception), close returns to its caller. If the generator
429 yields a value, a :exc:`RuntimeError` is raised. If the generator raises any
430 other exception, it is propagated to the caller. :meth:`close` does nothing
431 if the generator has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000432
433Here is a simple example that demonstrates the behavior of generators and
434generator functions::
435
436 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000437 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000438 ... try:
439 ... while True:
440 ... try:
441 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000442 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000443 ... value = e
444 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000445 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000446 ...
447 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000448 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000449 Execution starts when 'next()' is called for the first time.
450 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000451 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000452 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000453 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000454 2
455 >>> generator.throw(TypeError, "spam")
456 TypeError('spam',)
457 >>> generator.close()
458 Don't forget to clean up when 'close()' is called.
459
460
461.. seealso::
462
Georg Brandl02c30562007-09-07 17:52:53 +0000463 :pep:`0255` - Simple Generators
464 The proposal for adding generators and the :keyword:`yield` statement to Python.
465
Georg Brandl116aa622007-08-15 14:28:22 +0000466 :pep:`0342` - Coroutines via Enhanced Generators
Georg Brandl96593ed2007-09-07 14:15:41 +0000467 The proposal to enhance the API and syntax of generators, making them
468 usable as simple coroutines.
Georg Brandl116aa622007-08-15 14:28:22 +0000469
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000470 :pep:`0380` - Syntax for Delegating to a Subgenerator
471 The proposal to introduce the :token:`yield_from` syntax, making delegation
472 to sub-generators easy.
473
Georg Brandl116aa622007-08-15 14:28:22 +0000474
475.. _primaries:
476
477Primaries
478=========
479
480.. index:: single: primary
481
482Primaries represent the most tightly bound operations of the language. Their
483syntax is:
484
485.. productionlist::
486 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
487
488
489.. _attribute-references:
490
491Attribute references
492--------------------
493
494.. index:: pair: attribute; reference
495
496An attribute reference is a primary followed by a period and a name:
497
498.. productionlist::
499 attributeref: `primary` "." `identifier`
500
501.. index::
502 exception: AttributeError
503 object: module
504 object: list
505
506The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000507references, which most objects do. This object is then asked to produce the
508attribute whose name is the identifier (which can be customized by overriding
509the :meth:`__getattr__` method). If this attribute is not available, the
510exception :exc:`AttributeError` is raised. Otherwise, the type and value of the
511object produced is determined by the object. Multiple evaluations of the same
512attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000513
514
515.. _subscriptions:
516
517Subscriptions
518-------------
519
520.. index:: single: subscription
521
522.. index::
523 object: sequence
524 object: mapping
525 object: string
526 object: tuple
527 object: list
528 object: dictionary
529 pair: sequence; item
530
531A subscription selects an item of a sequence (string, tuple or list) or mapping
532(dictionary) object:
533
534.. productionlist::
535 subscription: `primary` "[" `expression_list` "]"
536
Georg Brandl96593ed2007-09-07 14:15:41 +0000537The primary must evaluate to an object that supports subscription, e.g. a list
538or dictionary. User-defined objects can support subscription by defining a
539:meth:`__getitem__` method.
540
541For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000542
543If the primary is a mapping, the expression list must evaluate to an object
544whose value is one of the keys of the mapping, and the subscription selects the
545value in the mapping that corresponds to that key. (The expression list is a
546tuple except if it has exactly one item.)
547
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000548If the primary is a sequence, the expression (list) must evaluate to an integer
549or a slice (as discussed in the following section).
550
551The formal syntax makes no special provision for negative indices in
552sequences; however, built-in sequences all provide a :meth:`__getitem__`
553method that interprets negative indices by adding the length of the sequence
554to the index (so that ``x[-1]`` selects the last item of ``x``). The
555resulting value must be a nonnegative integer less than the number of items in
556the sequence, and the subscription selects the item whose index is that value
557(counting from zero). Since the support for negative indices and slicing
558occurs in the object's :meth:`__getitem__` method, subclasses overriding
559this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000560
561.. index::
562 single: character
563 pair: string; item
564
565A string's items are characters. A character is not a separate data type but a
566string of exactly one character.
567
568
569.. _slicings:
570
571Slicings
572--------
573
574.. index::
575 single: slicing
576 single: slice
577
578.. index::
579 object: sequence
580 object: string
581 object: tuple
582 object: list
583
584A slicing selects a range of items in a sequence object (e.g., a string, tuple
585or list). Slicings may be used as expressions or as targets in assignment or
586:keyword:`del` statements. The syntax for a slicing:
587
588.. productionlist::
Georg Brandl48310cd2009-01-03 21:18:54 +0000589 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000590 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000591 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000592 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000593 lower_bound: `expression`
594 upper_bound: `expression`
595 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000596
597There is ambiguity in the formal syntax here: anything that looks like an
598expression list also looks like a slice list, so any subscription can be
599interpreted as a slicing. Rather than further complicating the syntax, this is
600disambiguated by defining that in this case the interpretation as a subscription
601takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000602slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000603
604.. index::
605 single: start (slice object attribute)
606 single: stop (slice object attribute)
607 single: step (slice object attribute)
608
Thomas Wouters53de1902007-09-04 09:03:59 +0000609The semantics for a slicing are as follows. The primary must evaluate to a
Georg Brandl96593ed2007-09-07 14:15:41 +0000610mapping object, and it is indexed (using the same :meth:`__getitem__` method as
611normal subscription) with a key that is constructed from the slice list, as
612follows. If the slice list contains at least one comma, the key is a tuple
613containing the conversion of the slice items; otherwise, the conversion of the
614lone slice item is the key. The conversion of a slice item that is an
615expression is that expression. The conversion of a proper slice is a slice
616object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and
617:attr:`step` attributes are the values of the expressions given as lower bound,
618upper bound and stride, respectively, substituting ``None`` for missing
619expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000620
621
622.. _calls:
623
624Calls
625-----
626
627.. index:: single: call
628
629.. index:: object: callable
630
631A call calls a callable object (e.g., a function) with a possibly empty series
632of arguments:
633
634.. productionlist::
Georg Brandldc529c12008-09-21 17:03:29 +0000635 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Georg Brandl116aa622007-08-15 14:28:22 +0000636 argument_list: `positional_arguments` ["," `keyword_arguments`]
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000637 : ["," "*" `expression`] ["," `keyword_arguments`]
638 : ["," "**" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000639 : | `keyword_arguments` ["," "*" `expression`]
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000640 : ["," `keyword_arguments`] ["," "**" `expression`]
641 : | "*" `expression` ["," `keyword_arguments`] ["," "**" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000642 : | "**" `expression`
643 positional_arguments: `expression` ("," `expression`)*
644 keyword_arguments: `keyword_item` ("," `keyword_item`)*
645 keyword_item: `identifier` "=" `expression`
646
647A trailing comma may be present after the positional and keyword arguments but
648does not affect the semantics.
649
650The primary must evaluate to a callable object (user-defined functions, built-in
651functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000652instances, and all objects having a :meth:`__call__` method are callable). All
653argument expressions are evaluated before the call is attempted. Please refer
654to section :ref:`function` for the syntax of formal parameter lists.
655
656.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000657
658If keyword arguments are present, they are first converted to positional
659arguments, as follows. First, a list of unfilled slots is created for the
660formal parameters. If there are N positional arguments, they are placed in the
661first N slots. Next, for each keyword argument, the identifier is used to
662determine the corresponding slot (if the identifier is the same as the first
663formal parameter name, the first slot is used, and so on). If the slot is
664already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
665the argument is placed in the slot, filling it (even if the expression is
666``None``, it fills the slot). When all arguments have been processed, the slots
667that are still unfilled are filled with the corresponding default value from the
668function definition. (Default values are calculated, once, when the function is
669defined; thus, a mutable object such as a list or dictionary used as default
670value will be shared by all calls that don't specify an argument value for the
671corresponding slot; this should usually be avoided.) If there are any unfilled
672slots for which no default value is specified, a :exc:`TypeError` exception is
673raised. Otherwise, the list of filled slots is used as the argument list for
674the call.
675
Georg Brandl495f7b52009-10-27 15:28:25 +0000676.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000677
Georg Brandl495f7b52009-10-27 15:28:25 +0000678 An implementation may provide built-in functions whose positional parameters
679 do not have names, even if they are 'named' for the purpose of documentation,
680 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000681 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000682 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000683
Georg Brandl116aa622007-08-15 14:28:22 +0000684If there are more positional arguments than there are formal parameter slots, a
685:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
686``*identifier`` is present; in this case, that formal parameter receives a tuple
687containing the excess positional arguments (or an empty tuple if there were no
688excess positional arguments).
689
690If any keyword argument does not correspond to a formal parameter name, a
691:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
692``**identifier`` is present; in this case, that formal parameter receives a
693dictionary containing the excess keyword arguments (using the keywords as keys
694and the argument values as corresponding values), or a (new) empty dictionary if
695there were no excess keyword arguments.
696
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300697.. index::
698 single: *; in function calls
699
Georg Brandl116aa622007-08-15 14:28:22 +0000700If the syntax ``*expression`` appears in the function call, ``expression`` must
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300701evaluate to an iterable. Elements from this iterable are treated as if they
702were additional positional arguments; if there are positional arguments
Ezio Melotti59256322011-07-30 21:25:22 +0300703*x1*, ..., *xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*,
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300704this is equivalent to a call with M+N positional arguments *x1*, ..., *xN*,
705*y1*, ..., *yM*.
Georg Brandl116aa622007-08-15 14:28:22 +0000706
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000707A consequence of this is that although the ``*expression`` syntax may appear
708*after* some keyword arguments, it is processed *before* the keyword arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000709(and the ``**expression`` argument, if any -- see below). So::
710
711 >>> def f(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000712 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000713 ...
714 >>> f(b=1, *(2,))
715 2 1
716 >>> f(a=1, *(2,))
717 Traceback (most recent call last):
718 File "<stdin>", line 1, in ?
719 TypeError: f() got multiple values for keyword argument 'a'
720 >>> f(1, *(2,))
721 1 2
722
723It is unusual for both keyword arguments and the ``*expression`` syntax to be
724used in the same call, so in practice this confusion does not arise.
725
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300726.. index::
727 single: **; in function calls
728
Georg Brandl116aa622007-08-15 14:28:22 +0000729If the syntax ``**expression`` appears in the function call, ``expression`` must
730evaluate to a mapping, the contents of which are treated as additional keyword
731arguments. In the case of a keyword appearing in both ``expression`` and as an
732explicit keyword argument, a :exc:`TypeError` exception is raised.
733
734Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
735used as positional argument slots or as keyword argument names.
736
737A call always returns some value, possibly ``None``, unless it raises an
738exception. How this value is computed depends on the type of the callable
739object.
740
741If it is---
742
743a user-defined function:
744 .. index::
745 pair: function; call
746 triple: user-defined; function; call
747 object: user-defined function
748 object: function
749
750 The code block for the function is executed, passing it the argument list. The
751 first thing the code block will do is bind the formal parameters to the
752 arguments; this is described in section :ref:`function`. When the code block
753 executes a :keyword:`return` statement, this specifies the return value of the
754 function call.
755
756a built-in function or method:
757 .. index::
758 pair: function; call
759 pair: built-in function; call
760 pair: method; call
761 pair: built-in method; call
762 object: built-in method
763 object: built-in function
764 object: method
765 object: function
766
767 The result is up to the interpreter; see :ref:`built-in-funcs` for the
768 descriptions of built-in functions and methods.
769
770a class object:
771 .. index::
772 object: class
773 pair: class object; call
774
775 A new instance of that class is returned.
776
777a class instance method:
778 .. index::
779 object: class instance
780 object: instance
781 pair: class instance; call
782
783 The corresponding user-defined function is called, with an argument list that is
784 one longer than the argument list of the call: the instance becomes the first
785 argument.
786
787a class instance:
788 .. index::
789 pair: instance; call
790 single: __call__() (object method)
791
792 The class must define a :meth:`__call__` method; the effect is then the same as
793 if that method was called.
794
795
796.. _power:
797
798The power operator
799==================
800
801The power operator binds more tightly than unary operators on its left; it binds
802less tightly than unary operators on its right. The syntax is:
803
804.. productionlist::
805 power: `primary` ["**" `u_expr`]
806
807Thus, in an unparenthesized sequence of power and unary operators, the operators
808are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +0000809for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811The power operator has the same semantics as the built-in :func:`pow` function,
812when called with two arguments: it yields its left argument raised to the power
813of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +0000814type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +0000815
Georg Brandl96593ed2007-09-07 14:15:41 +0000816For int operands, the result has the same type as the operands unless the second
817argument is negative; in that case, all arguments are converted to float and a
818float result is delivered. For example, ``10**2`` returns ``100``, but
819``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +0000820
821Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +0000822Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +0000823number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000824
825
826.. _unary:
827
Benjamin Petersonba01dd92009-02-20 04:02:38 +0000828Unary arithmetic and bitwise operations
829=======================================
Georg Brandl116aa622007-08-15 14:28:22 +0000830
831.. index::
832 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +0000833 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000834
Benjamin Petersonba01dd92009-02-20 04:02:38 +0000835All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +0000836
837.. productionlist::
838 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
839
840.. index::
841 single: negation
842 single: minus
843
844The unary ``-`` (minus) operator yields the negation of its numeric argument.
845
846.. index:: single: plus
847
848The unary ``+`` (plus) operator yields its numeric argument unchanged.
849
850.. index:: single: inversion
851
Christian Heimesfaf2f632008-01-06 16:59:19 +0000852
Georg Brandl95817b32008-05-11 14:30:18 +0000853The unary ``~`` (invert) operator yields the bitwise inversion of its integer
854argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
855applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000856
857.. index:: exception: TypeError
858
859In all three cases, if the argument does not have the proper type, a
860:exc:`TypeError` exception is raised.
861
862
863.. _binary:
864
865Binary arithmetic operations
866============================
867
868.. index:: triple: binary; arithmetic; operation
869
870The binary arithmetic operations have the conventional priority levels. Note
871that some of these operations also apply to certain non-numeric types. Apart
872from the power operator, there are only two levels, one for multiplicative
873operators and one for additive operators:
874
875.. productionlist::
876 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
877 : | `m_expr` "%" `u_expr`
878 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
879
880.. index:: single: multiplication
881
882The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +0000883arguments must either both be numbers, or one argument must be an integer and
884the other must be a sequence. In the former case, the numbers are converted to a
885common type and then multiplied together. In the latter case, sequence
886repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000887
888.. index::
889 exception: ZeroDivisionError
890 single: division
891
892The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
893their arguments. The numeric arguments are first converted to a common type.
Georg Brandl96593ed2007-09-07 14:15:41 +0000894Integer division yields a float, while floor division of integers results in an
895integer; the result is that of mathematical division with the 'floor' function
896applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
897exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000898
899.. index:: single: modulo
900
901The ``%`` (modulo) operator yields the remainder from the division of the first
902argument by the second. The numeric arguments are first converted to a common
903type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
904arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
905(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
906result with the same sign as its second operand (or zero); the absolute value of
907the result is strictly smaller than the absolute value of the second operand
908[#]_.
909
Georg Brandl96593ed2007-09-07 14:15:41 +0000910The floor division and modulo operators are connected by the following
911identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
912connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
913x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000914
915In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +0000916also overloaded by string objects to perform old-style string formatting (also
917known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +0000918Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +0000919
920The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +0000921function are not defined for complex numbers. Instead, convert to a floating
922point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +0000923
924.. index:: single: addition
925
Georg Brandl96593ed2007-09-07 14:15:41 +0000926The ``+`` (addition) operator yields the sum of its arguments. The arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000927must either both be numbers or both sequences of the same type. In the former
928case, the numbers are converted to a common type and then added together. In
929the latter case, the sequences are concatenated.
930
931.. index:: single: subtraction
932
933The ``-`` (subtraction) operator yields the difference of its arguments. The
934numeric arguments are first converted to a common type.
935
936
937.. _shifting:
938
939Shifting operations
940===================
941
942.. index:: pair: shifting; operation
943
944The shifting operations have lower priority than the arithmetic operations:
945
946.. productionlist::
947 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
948
Georg Brandl96593ed2007-09-07 14:15:41 +0000949These operators accept integers as arguments. They shift the first argument to
950the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000951
952.. index:: exception: ValueError
953
954A right shift by *n* bits is defined as division by ``pow(2,n)``. A left shift
Georg Brandl96593ed2007-09-07 14:15:41 +0000955by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000956
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000957.. note::
958
959 In the current implementation, the right-hand operand is required
Mark Dickinson505add32010-04-06 18:22:06 +0000960 to be at most :attr:`sys.maxsize`. If the right-hand operand is larger than
961 :attr:`sys.maxsize` an :exc:`OverflowError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000962
963.. _bitwise:
964
Christian Heimesfaf2f632008-01-06 16:59:19 +0000965Binary bitwise operations
966=========================
Georg Brandl116aa622007-08-15 14:28:22 +0000967
Christian Heimesfaf2f632008-01-06 16:59:19 +0000968.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000969
970Each of the three bitwise operations has a different priority level:
971
972.. productionlist::
973 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
974 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
975 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
976
Christian Heimesfaf2f632008-01-06 16:59:19 +0000977.. index:: pair: bitwise; and
Georg Brandl116aa622007-08-15 14:28:22 +0000978
Georg Brandl96593ed2007-09-07 14:15:41 +0000979The ``&`` operator yields the bitwise AND of its arguments, which must be
980integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000981
982.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +0000983 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +0000984 pair: exclusive; or
985
986The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +0000987must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000988
989.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +0000990 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +0000991 pair: inclusive; or
992
993The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +0000994must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000995
996
997.. _comparisons:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000998.. _is:
Georg Brandl375aec22011-01-15 17:03:02 +0000999.. _is not:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001000.. _in:
Georg Brandl375aec22011-01-15 17:03:02 +00001001.. _not in:
Georg Brandl116aa622007-08-15 14:28:22 +00001002
1003Comparisons
1004===========
1005
1006.. index:: single: comparison
1007
1008.. index:: pair: C; language
1009
1010Unlike C, all comparison operations in Python have the same priority, which is
1011lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1012C, expressions like ``a < b < c`` have the interpretation that is conventional
1013in mathematics:
1014
1015.. productionlist::
1016 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1017 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1018 : | "is" ["not"] | ["not"] "in"
1019
1020Comparisons yield boolean values: ``True`` or ``False``.
1021
1022.. index:: pair: chaining; comparisons
1023
1024Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1025``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1026cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1027
Guido van Rossum04110fb2007-08-24 16:32:05 +00001028Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1029*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1030to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1031evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001032
Guido van Rossum04110fb2007-08-24 16:32:05 +00001033Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001034*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1035pretty).
1036
1037The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1038values of two objects. The objects need not have the same type. If both are
Georg Brandl9609cea2008-09-09 19:31:57 +00001039numbers, they are converted to a common type. Otherwise, the ``==`` and ``!=``
1040operators *always* consider objects of different types to be unequal, while the
1041``<``, ``>``, ``>=`` and ``<=`` operators raise a :exc:`TypeError` when
1042comparing objects of different types that do not implement these operators for
1043the given pair of types. You can control comparison behavior of objects of
Georg Brandl22b34312009-07-26 14:54:51 +00001044non-built-in types by defining rich comparison methods like :meth:`__gt__`,
Georg Brandl9609cea2008-09-09 19:31:57 +00001045described in section :ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001046
1047Comparison of objects of the same type depends on the type:
1048
1049* Numbers are compared arithmetically.
1050
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001051* The values :const:`float('NaN')` and :const:`Decimal('NaN')` are special.
1052 The are identical to themselves, ``x is x`` but are not equal to themselves,
1053 ``x != x``. Additionally, comparing any value to a not-a-number value
1054 will return ``False``. For example, both ``3 < float('NaN')`` and
1055 ``float('NaN') < 3`` will return ``False``.
1056
Georg Brandl96593ed2007-09-07 14:15:41 +00001057* Bytes objects are compared lexicographically using the numeric values of their
1058 elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001059
Georg Brandl116aa622007-08-15 14:28:22 +00001060* Strings are compared lexicographically using the numeric equivalents (the
Georg Brandl96593ed2007-09-07 14:15:41 +00001061 result of the built-in function :func:`ord`) of their characters. [#]_ String
1062 and bytes object can't be compared!
Georg Brandl116aa622007-08-15 14:28:22 +00001063
1064* Tuples and lists are compared lexicographically using comparison of
1065 corresponding elements. This means that to compare equal, each element must
1066 compare equal and the two sequences must be of the same type and have the same
1067 length.
1068
1069 If not equal, the sequences are ordered the same as their first differing
Mark Dickinsonc48d8342009-02-01 14:18:10 +00001070 elements. For example, ``[1,2,x] <= [1,2,y]`` has the same value as
1071 ``x <= y``. If the corresponding element does not exist, the shorter
Georg Brandl96593ed2007-09-07 14:15:41 +00001072 sequence is ordered first (for example, ``[1,2] < [1,2,3]``).
Georg Brandl116aa622007-08-15 14:28:22 +00001073
Senthil Kumaran07367672010-07-14 20:30:02 +00001074* Mappings (dictionaries) compare equal if and only if they have the same
1075 ``(key, value)`` pairs. Order comparisons ``('<', '<=', '>=', '>')``
1076 raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001077
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001078* Sets and frozensets define comparison operators to mean subset and superset
1079 tests. Those relations do not define total orderings (the two sets ``{1,2}``
1080 and {2,3} are not equal, nor subsets of one another, nor supersets of one
1081 another). Accordingly, sets are not appropriate arguments for functions
1082 which depend on total ordering. For example, :func:`min`, :func:`max`, and
1083 :func:`sorted` produce undefined results given a list of sets as inputs.
1084
Georg Brandl22b34312009-07-26 14:54:51 +00001085* Most other objects of built-in types compare unequal unless they are the same
Georg Brandl116aa622007-08-15 14:28:22 +00001086 object; the choice whether one object is considered smaller or larger than
1087 another one is made arbitrarily but consistently within one execution of a
1088 program.
1089
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001090Comparison of objects of the differing types depends on whether either
Raymond Hettinger0cc818f2008-11-21 10:40:51 +00001091of the types provide explicit support for the comparison. Most numeric types
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001092can be compared with one another, but comparisons of :class:`float` and
Georg Brandl48310cd2009-01-03 21:18:54 +00001093:class:`Decimal` are not supported to avoid the inevitable confusion arising
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001094from representation issues such as ``float('1.1')`` being inexactly represented
1095and therefore not exactly equal to ``Decimal('1.1')`` which is. When
1096cross-type comparison is not supported, the comparison method returns
1097``NotImplemented``. This can create the illusion of non-transitivity between
1098supported cross-type comparisons and unsupported comparisons. For example,
Georg Brandl682d7e02010-10-06 10:26:05 +00001099``Decimal(2) == 2`` and ``2 == float(2)`` but ``Decimal(2) != float(2)``.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001100
Georg Brandl495f7b52009-10-27 15:28:25 +00001101.. _membership-test-details:
1102
Georg Brandl96593ed2007-09-07 14:15:41 +00001103The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
1104s`` evaluates to true if *x* is a member of *s*, and false otherwise. ``x not
1105in s`` returns the negation of ``x in s``. All built-in sequences and set types
1106support this as well as dictionary, for which :keyword:`in` tests whether a the
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001107dictionary has a given key. For container types such as list, tuple, set,
Raymond Hettinger0cc818f2008-11-21 10:40:51 +00001108frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001109to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001110
Georg Brandl4b491312007-08-31 09:22:56 +00001111For the string and bytes types, ``x in y`` is true if and only if *x* is a
1112substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1113always considered to be a substring of any other string, so ``"" in "abc"`` will
1114return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001115
Georg Brandl116aa622007-08-15 14:28:22 +00001116For user-defined classes which define the :meth:`__contains__` method, ``x in
1117y`` is true if and only if ``y.__contains__(x)`` is true.
1118
Georg Brandl495f7b52009-10-27 15:28:25 +00001119For user-defined classes which do not define :meth:`__contains__` but do define
1120:meth:`__iter__`, ``x in y`` is true if some value ``z`` with ``x == z`` is
1121produced while iterating over ``y``. If an exception is raised during the
1122iteration, it is as if :keyword:`in` raised that exception.
1123
1124Lastly, the old-style iteration protocol is tried: if a class defines
Georg Brandl116aa622007-08-15 14:28:22 +00001125:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1126integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001127raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001128if :keyword:`in` raised that exception).
1129
1130.. index::
1131 operator: in
1132 operator: not in
1133 pair: membership; test
1134 object: sequence
1135
1136The operator :keyword:`not in` is defined to have the inverse true value of
1137:keyword:`in`.
1138
1139.. index::
1140 operator: is
1141 operator: is not
1142 pair: identity; test
1143
1144The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1145is y`` is true if and only if *x* and *y* are the same object. ``x is not y``
Benjamin Peterson41181742008-07-02 20:22:54 +00001146yields the inverse truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001147
1148
1149.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001150.. _and:
1151.. _or:
1152.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001153
1154Boolean operations
1155==================
1156
1157.. index::
1158 pair: Conditional; expression
1159 pair: Boolean; operation
1160
Georg Brandl116aa622007-08-15 14:28:22 +00001161.. productionlist::
Georg Brandl116aa622007-08-15 14:28:22 +00001162 or_test: `and_test` | `or_test` "or" `and_test`
1163 and_test: `not_test` | `and_test` "and" `not_test`
1164 not_test: `comparison` | "not" `not_test`
1165
1166In the context of Boolean operations, and also when expressions are used by
1167control flow statements, the following values are interpreted as false:
1168``False``, ``None``, numeric zero of all types, and empty strings and containers
1169(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001170other values are interpreted as true. User-defined objects can customize their
1171truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001172
1173.. index:: operator: not
1174
1175The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1176otherwise.
1177
Georg Brandl116aa622007-08-15 14:28:22 +00001178.. index:: operator: and
1179
1180The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1181returned; otherwise, *y* is evaluated and the resulting value is returned.
1182
1183.. index:: operator: or
1184
1185The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1186returned; otherwise, *y* is evaluated and the resulting value is returned.
1187
1188(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1189they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001190argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001191replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1192the desired value. Because :keyword:`not` has to invent a value anyway, it does
1193not bother to return a value of the same type as its argument, so e.g., ``not
1194'foo'`` yields ``False``, not ``''``.)
1195
1196
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001197Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001198=======================
1199
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001200.. index::
1201 pair: conditional; expression
1202 pair: ternary; operator
1203
1204.. productionlist::
1205 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1206 expression: `conditional_expression` | `lambda_form`
1207 expression_nocond: `or_test` | `lambda_form_nocond`
1208
1209Conditional expressions (sometimes called a "ternary operator") have the lowest
1210priority of all Python operations.
1211
1212The expression ``x if C else y`` first evaluates the condition, *C* (*not* *x*);
1213if *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
1214evaluated and its value is returned.
1215
1216See :pep:`308` for more details about conditional expressions.
1217
1218
Georg Brandl116aa622007-08-15 14:28:22 +00001219.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001220.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001221
1222Lambdas
1223=======
1224
1225.. index::
1226 pair: lambda; expression
1227 pair: lambda; form
1228 pair: anonymous; function
1229
1230.. productionlist::
1231 lambda_form: "lambda" [`parameter_list`]: `expression`
Georg Brandl96593ed2007-09-07 14:15:41 +00001232 lambda_form_nocond: "lambda" [`parameter_list`]: `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001233
1234Lambda forms (lambda expressions) have the same syntactic position as
1235expressions. They are a shorthand to create anonymous functions; the expression
1236``lambda arguments: expression`` yields a function object. The unnamed object
1237behaves like a function object defined with ::
1238
Georg Brandl96593ed2007-09-07 14:15:41 +00001239 def <lambda>(arguments):
Georg Brandl116aa622007-08-15 14:28:22 +00001240 return expression
1241
1242See section :ref:`function` for the syntax of parameter lists. Note that
1243functions created with lambda forms cannot contain statements or annotations.
1244
Georg Brandl116aa622007-08-15 14:28:22 +00001245
1246.. _exprlists:
1247
1248Expression lists
1249================
1250
1251.. index:: pair: expression; list
1252
1253.. productionlist::
1254 expression_list: `expression` ( "," `expression` )* [","]
1255
1256.. index:: object: tuple
1257
1258An expression list containing at least one comma yields a tuple. The length of
1259the tuple is the number of expressions in the list. The expressions are
1260evaluated from left to right.
1261
1262.. index:: pair: trailing; comma
1263
1264The trailing comma is required only to create a single tuple (a.k.a. a
1265*singleton*); it is optional in all other cases. A single expression without a
1266trailing comma doesn't create a tuple, but rather yields the value of that
1267expression. (To create an empty tuple, use an empty pair of parentheses:
1268``()``.)
1269
1270
1271.. _evalorder:
1272
1273Evaluation order
1274================
1275
1276.. index:: pair: evaluation; order
1277
Georg Brandl96593ed2007-09-07 14:15:41 +00001278Python evaluates expressions from left to right. Notice that while evaluating
1279an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001280
1281In the following lines, expressions will be evaluated in the arithmetic order of
1282their suffixes::
1283
1284 expr1, expr2, expr3, expr4
1285 (expr1, expr2, expr3, expr4)
1286 {expr1: expr2, expr3: expr4}
1287 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001288 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001289 expr3, expr4 = expr1, expr2
1290
1291
1292.. _operator-summary:
1293
1294Summary
1295=======
1296
1297.. index:: pair: operator; precedence
1298
1299The following table summarizes the operator precedences in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001300precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001301the same box have the same precedence. Unless the syntax is explicitly given,
1302operators are binary. Operators in the same box group left to right (except for
1303comparisons, including tests, which all have the same precedence and chain from
1304left to right --- see section :ref:`comparisons` --- and exponentiation, which
1305groups from right to left).
1306
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001307
1308+-----------------------------------------------+-------------------------------------+
1309| Operator | Description |
1310+===============================================+=====================================+
1311| :keyword:`lambda` | Lambda expression |
1312+-----------------------------------------------+-------------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001313| :keyword:`if` -- :keyword:`else` | Conditional expression |
1314+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001315| :keyword:`or` | Boolean OR |
1316+-----------------------------------------------+-------------------------------------+
1317| :keyword:`and` | Boolean AND |
1318+-----------------------------------------------+-------------------------------------+
1319| :keyword:`not` *x* | Boolean NOT |
1320+-----------------------------------------------+-------------------------------------+
1321| :keyword:`in`, :keyword:`not` :keyword:`in`, | Comparisons, including membership |
1322| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests, |
Georg Brandla5ebc262009-06-03 07:26:22 +00001323| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001324+-----------------------------------------------+-------------------------------------+
1325| ``|`` | Bitwise OR |
1326+-----------------------------------------------+-------------------------------------+
1327| ``^`` | Bitwise XOR |
1328+-----------------------------------------------+-------------------------------------+
1329| ``&`` | Bitwise AND |
1330+-----------------------------------------------+-------------------------------------+
1331| ``<<``, ``>>`` | Shifts |
1332+-----------------------------------------------+-------------------------------------+
1333| ``+``, ``-`` | Addition and subtraction |
1334+-----------------------------------------------+-------------------------------------+
1335| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |
Georg Brandlf1d633c2010-09-20 06:29:01 +00001336| | [#]_ |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001337+-----------------------------------------------+-------------------------------------+
1338| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1339+-----------------------------------------------+-------------------------------------+
1340| ``**`` | Exponentiation [#]_ |
1341+-----------------------------------------------+-------------------------------------+
1342| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1343| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1344+-----------------------------------------------+-------------------------------------+
1345| ``(expressions...)``, | Binding or tuple display, |
1346| ``[expressions...]``, | list display, |
1347| ``{key:datum...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001348| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001349+-----------------------------------------------+-------------------------------------+
1350
Georg Brandl116aa622007-08-15 14:28:22 +00001351
1352.. rubric:: Footnotes
1353
Georg Brandl116aa622007-08-15 14:28:22 +00001354.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1355 true numerically due to roundoff. For example, and assuming a platform on which
1356 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1357 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001358 1e100``, which is numerically exactly equal to ``1e100``. The function
1359 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001360 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1361 is more appropriate depends on the application.
1362
1363.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001364 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001365 cases, Python returns the latter result, in order to preserve that
1366 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1367
Georg Brandl96593ed2007-09-07 14:15:41 +00001368.. [#] While comparisons between strings make sense at the byte level, they may
1369 be counter-intuitive to users. For example, the strings ``"\u00C7"`` and
1370 ``"\u0327\u0043"`` compare differently, even though they both represent the
Georg Brandlae2dbe22009-03-13 19:04:40 +00001371 same unicode character (LATIN CAPITAL LETTER C WITH CEDILLA). To compare
Georg Brandl9afde1c2007-11-01 20:32:30 +00001372 strings in a human recognizable way, compare using
1373 :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001374
Georg Brandl48310cd2009-01-03 21:18:54 +00001375.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001376 descriptors, you may notice seemingly unusual behaviour in certain uses of
1377 the :keyword:`is` operator, like those involving comparisons between instance
1378 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001379
Georg Brandl063f2372010-12-01 15:32:43 +00001380.. [#] The ``%`` operator is also used for string formatting; the same
1381 precedence applies.
Georg Brandlf1d633c2010-09-20 06:29:01 +00001382
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001383.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1384 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.