blob: 68de3c85cde3410bf4ca81aa5d9a5426d459cc87 [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
Terry Jan Reedyead1de22012-02-17 19:56:58 -0500119All literals correspond to immutable data types, and hence the object's identity
120is less important than its value. Multiple evaluations of literals with the
121same value (either the same occurrence in the program text or a different
122occurrence) may obtain the same object or a different object with the same
123value.
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
Ezio Melotti7fa82222012-10-12 13:42:08 +0300297:meth:`~generator.__next__` method is called for generator object (in the same
298fashion as normal generators). However, the leftmost :keyword:`for` clause is
299immediately evaluated, so that an error produced by it can be seen before any
300other possible error in the code that handles the generator expression.
301Subsequent :keyword:`for` clauses cannot be evaluated immediately since they
302may depend on the previous :keyword:`for` loop. For example: ``(x*y for x in
303range(10) for y in bar(x))``.
Georg Brandl96593ed2007-09-07 14:15:41 +0000304
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` ")"
321 yield_expression: "yield" [`expression_list`]
322
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
339the execution.
340
341.. index:: single: coroutine
342
343All of this makes generator functions quite similar to coroutines; they yield
344multiple times, they have more than one entry point and their execution can be
345suspended. The only difference is that a generator function cannot control
346where should the execution continue after it yields; the control is always
Georg Brandl6faee4e2010-09-21 14:48:28 +0000347transferred to the generator's caller.
Georg Brandl116aa622007-08-15 14:28:22 +0000348
Georg Brandl02c30562007-09-07 17:52:53 +0000349The :keyword:`yield` statement is allowed in the :keyword:`try` clause of a
350:keyword:`try` ... :keyword:`finally` construct. If the generator is not
351resumed before it is finalized (by reaching a zero reference count or by being
352garbage collected), the generator-iterator's :meth:`close` method will be
353called, allowing any pending :keyword:`finally` clauses to execute.
354
Georg Brandl116aa622007-08-15 14:28:22 +0000355.. index:: object: generator
356
R David Murray2c1d1d62012-08-17 20:48:59 -0400357
358Generator-iterator methods
359^^^^^^^^^^^^^^^^^^^^^^^^^^
360
361This subsection describes the methods of a generator iterator. They can
362be used to control the execution of a generator function.
363
364Note that calling any of the generator methods below when the generator
365is already executing raises a :exc:`ValueError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000366
367.. index:: exception: StopIteration
368
369
Georg Brandl96593ed2007-09-07 14:15:41 +0000370.. method:: generator.__next__()
Georg Brandl116aa622007-08-15 14:28:22 +0000371
Georg Brandl96593ed2007-09-07 14:15:41 +0000372 Starts the execution of a generator function or resumes it at the last
373 executed :keyword:`yield` expression. When a generator function is resumed
Ezio Melotti7fa82222012-10-12 13:42:08 +0300374 with a :meth:`~generator.__next__` method, the current :keyword:`yield`
375 expression always evaluates to :const:`None`. The execution then continues
376 to the next :keyword:`yield` expression, where the generator is suspended
377 again, and the value of the :token:`expression_list` is returned to
378 :meth:`next`'s caller.
Georg Brandl96593ed2007-09-07 14:15:41 +0000379 If the generator exits without yielding another value, a :exc:`StopIteration`
380 exception is raised.
381
382 This method is normally called implicitly, e.g. by a :keyword:`for` loop, or
383 by the built-in :func:`next` function.
Georg Brandl116aa622007-08-15 14:28:22 +0000384
385
386.. method:: generator.send(value)
387
388 Resumes the execution and "sends" a value into the generator function. The
389 ``value`` argument becomes the result of the current :keyword:`yield`
390 expression. The :meth:`send` method returns the next value yielded by the
391 generator, or raises :exc:`StopIteration` if the generator exits without
Georg Brandl96593ed2007-09-07 14:15:41 +0000392 yielding another value. When :meth:`send` is called to start the generator,
393 it must be called with :const:`None` as the argument, because there is no
Christian Heimesc3f30c42008-02-22 16:37:40 +0000394 :keyword:`yield` expression that could receive the value.
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396
397.. method:: generator.throw(type[, value[, traceback]])
398
399 Raises an exception of type ``type`` at the point where generator was paused,
400 and returns the next value yielded by the generator function. If the generator
401 exits without yielding another value, a :exc:`StopIteration` exception is
402 raised. If the generator function does not catch the passed-in exception, or
403 raises a different exception, then that exception propagates to the caller.
404
405.. index:: exception: GeneratorExit
406
407
408.. method:: generator.close()
409
410 Raises a :exc:`GeneratorExit` at the point where the generator function was
Georg Brandl96593ed2007-09-07 14:15:41 +0000411 paused. If the generator function then raises :exc:`StopIteration` (by
412 exiting normally, or due to already being closed) or :exc:`GeneratorExit` (by
413 not catching the exception), close returns to its caller. If the generator
414 yields a value, a :exc:`RuntimeError` is raised. If the generator raises any
415 other exception, it is propagated to the caller. :meth:`close` does nothing
416 if the generator has already exited due to an exception or normal exit.
Georg Brandl116aa622007-08-15 14:28:22 +0000417
418Here is a simple example that demonstrates the behavior of generators and
419generator functions::
420
421 >>> def echo(value=None):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000422 ... print("Execution starts when 'next()' is called for the first time.")
Georg Brandl116aa622007-08-15 14:28:22 +0000423 ... try:
424 ... while True:
425 ... try:
426 ... value = (yield value)
Georg Brandlfe800a32009-08-03 17:50:20 +0000427 ... except Exception as e:
Georg Brandl116aa622007-08-15 14:28:22 +0000428 ... value = e
429 ... finally:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000430 ... print("Don't forget to clean up when 'close()' is called.")
Georg Brandl116aa622007-08-15 14:28:22 +0000431 ...
432 >>> generator = echo(1)
Georg Brandl96593ed2007-09-07 14:15:41 +0000433 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000434 Execution starts when 'next()' is called for the first time.
435 1
Georg Brandl96593ed2007-09-07 14:15:41 +0000436 >>> print(next(generator))
Georg Brandl116aa622007-08-15 14:28:22 +0000437 None
Georg Brandl6911e3c2007-09-04 07:15:32 +0000438 >>> print(generator.send(2))
Georg Brandl116aa622007-08-15 14:28:22 +0000439 2
440 >>> generator.throw(TypeError, "spam")
441 TypeError('spam',)
442 >>> generator.close()
443 Don't forget to clean up when 'close()' is called.
444
445
446.. seealso::
447
Georg Brandl02c30562007-09-07 17:52:53 +0000448 :pep:`0255` - Simple Generators
449 The proposal for adding generators and the :keyword:`yield` statement to Python.
450
Georg Brandl116aa622007-08-15 14:28:22 +0000451 :pep:`0342` - Coroutines via Enhanced Generators
Georg Brandl96593ed2007-09-07 14:15:41 +0000452 The proposal to enhance the API and syntax of generators, making them
453 usable as simple coroutines.
Georg Brandl116aa622007-08-15 14:28:22 +0000454
455
456.. _primaries:
457
458Primaries
459=========
460
461.. index:: single: primary
462
463Primaries represent the most tightly bound operations of the language. Their
464syntax is:
465
466.. productionlist::
467 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
468
469
470.. _attribute-references:
471
472Attribute references
473--------------------
474
475.. index:: pair: attribute; reference
476
477An attribute reference is a primary followed by a period and a name:
478
479.. productionlist::
480 attributeref: `primary` "." `identifier`
481
482.. index::
483 exception: AttributeError
484 object: module
485 object: list
486
487The primary must evaluate to an object of a type that supports attribute
Georg Brandl96593ed2007-09-07 14:15:41 +0000488references, which most objects do. This object is then asked to produce the
489attribute whose name is the identifier (which can be customized by overriding
490the :meth:`__getattr__` method). If this attribute is not available, the
491exception :exc:`AttributeError` is raised. Otherwise, the type and value of the
492object produced is determined by the object. Multiple evaluations of the same
493attribute reference may yield different objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000494
495
496.. _subscriptions:
497
498Subscriptions
499-------------
500
501.. index:: single: subscription
502
503.. index::
504 object: sequence
505 object: mapping
506 object: string
507 object: tuple
508 object: list
509 object: dictionary
510 pair: sequence; item
511
512A subscription selects an item of a sequence (string, tuple or list) or mapping
513(dictionary) object:
514
515.. productionlist::
516 subscription: `primary` "[" `expression_list` "]"
517
Georg Brandl96593ed2007-09-07 14:15:41 +0000518The primary must evaluate to an object that supports subscription, e.g. a list
519or dictionary. User-defined objects can support subscription by defining a
520:meth:`__getitem__` method.
521
522For built-in objects, there are two types of objects that support subscription:
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524If the primary is a mapping, the expression list must evaluate to an object
525whose value is one of the keys of the mapping, and the subscription selects the
526value in the mapping that corresponds to that key. (The expression list is a
527tuple except if it has exactly one item.)
528
Raymond Hettingerf77c1d62010-09-15 00:09:26 +0000529If the primary is a sequence, the expression (list) must evaluate to an integer
530or a slice (as discussed in the following section).
531
532The formal syntax makes no special provision for negative indices in
533sequences; however, built-in sequences all provide a :meth:`__getitem__`
534method that interprets negative indices by adding the length of the sequence
535to the index (so that ``x[-1]`` selects the last item of ``x``). The
536resulting value must be a nonnegative integer less than the number of items in
537the sequence, and the subscription selects the item whose index is that value
538(counting from zero). Since the support for negative indices and slicing
539occurs in the object's :meth:`__getitem__` method, subclasses overriding
540this method will need to explicitly add that support.
Georg Brandl116aa622007-08-15 14:28:22 +0000541
542.. index::
543 single: character
544 pair: string; item
545
546A string's items are characters. A character is not a separate data type but a
547string of exactly one character.
548
549
550.. _slicings:
551
552Slicings
553--------
554
555.. index::
556 single: slicing
557 single: slice
558
559.. index::
560 object: sequence
561 object: string
562 object: tuple
563 object: list
564
565A slicing selects a range of items in a sequence object (e.g., a string, tuple
566or list). Slicings may be used as expressions or as targets in assignment or
567:keyword:`del` statements. The syntax for a slicing:
568
569.. productionlist::
Georg Brandl48310cd2009-01-03 21:18:54 +0000570 slicing: `primary` "[" `slice_list` "]"
Georg Brandl116aa622007-08-15 14:28:22 +0000571 slice_list: `slice_item` ("," `slice_item`)* [","]
Georg Brandlcb8ecb12007-09-04 06:35:14 +0000572 slice_item: `expression` | `proper_slice`
Thomas Wouters53de1902007-09-04 09:03:59 +0000573 proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ]
Georg Brandl116aa622007-08-15 14:28:22 +0000574 lower_bound: `expression`
575 upper_bound: `expression`
576 stride: `expression`
Georg Brandl116aa622007-08-15 14:28:22 +0000577
578There is ambiguity in the formal syntax here: anything that looks like an
579expression list also looks like a slice list, so any subscription can be
580interpreted as a slicing. Rather than further complicating the syntax, this is
581disambiguated by defining that in this case the interpretation as a subscription
582takes priority over the interpretation as a slicing (this is the case if the
Thomas Wouters53de1902007-09-04 09:03:59 +0000583slice list contains no proper slice).
Georg Brandl116aa622007-08-15 14:28:22 +0000584
585.. index::
586 single: start (slice object attribute)
587 single: stop (slice object attribute)
588 single: step (slice object attribute)
589
Thomas Wouters53de1902007-09-04 09:03:59 +0000590The semantics for a slicing are as follows. The primary must evaluate to a
Georg Brandl96593ed2007-09-07 14:15:41 +0000591mapping object, and it is indexed (using the same :meth:`__getitem__` method as
592normal subscription) with a key that is constructed from the slice list, as
593follows. If the slice list contains at least one comma, the key is a tuple
594containing the conversion of the slice items; otherwise, the conversion of the
595lone slice item is the key. The conversion of a slice item that is an
596expression is that expression. The conversion of a proper slice is a slice
597object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and
598:attr:`step` attributes are the values of the expressions given as lower bound,
599upper bound and stride, respectively, substituting ``None`` for missing
600expressions.
Georg Brandl116aa622007-08-15 14:28:22 +0000601
602
Chris Jerdonekb4309942012-12-25 14:54:44 -0800603.. index::
604 object: callable
605 single: call
606 single: argument; call semantics
607
Georg Brandl116aa622007-08-15 14:28:22 +0000608.. _calls:
609
610Calls
611-----
612
Chris Jerdonekb4309942012-12-25 14:54:44 -0800613A call calls a callable object (e.g., a :term:`function`) with a possibly empty
614series of :term:`arguments <argument>`:
Georg Brandl116aa622007-08-15 14:28:22 +0000615
616.. productionlist::
Georg Brandldc529c12008-09-21 17:03:29 +0000617 call: `primary` "(" [`argument_list` [","] | `comprehension`] ")"
Georg Brandl116aa622007-08-15 14:28:22 +0000618 argument_list: `positional_arguments` ["," `keyword_arguments`]
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000619 : ["," "*" `expression`] ["," `keyword_arguments`]
620 : ["," "**" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000621 : | `keyword_arguments` ["," "*" `expression`]
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000622 : ["," `keyword_arguments`] ["," "**" `expression`]
623 : | "*" `expression` ["," `keyword_arguments`] ["," "**" `expression`]
Georg Brandl116aa622007-08-15 14:28:22 +0000624 : | "**" `expression`
625 positional_arguments: `expression` ("," `expression`)*
626 keyword_arguments: `keyword_item` ("," `keyword_item`)*
627 keyword_item: `identifier` "=" `expression`
628
629A trailing comma may be present after the positional and keyword arguments but
630does not affect the semantics.
631
Chris Jerdonekb4309942012-12-25 14:54:44 -0800632.. index::
633 single: parameter; call semantics
634
Georg Brandl116aa622007-08-15 14:28:22 +0000635The primary must evaluate to a callable object (user-defined functions, built-in
636functions, methods of built-in objects, class objects, methods of class
Georg Brandl96593ed2007-09-07 14:15:41 +0000637instances, and all objects having a :meth:`__call__` method are callable). All
638argument expressions are evaluated before the call is attempted. Please refer
Chris Jerdonekb4309942012-12-25 14:54:44 -0800639to section :ref:`function` for the syntax of formal :term:`parameter` lists.
Georg Brandl96593ed2007-09-07 14:15:41 +0000640
641.. XXX update with kwonly args PEP
Georg Brandl116aa622007-08-15 14:28:22 +0000642
643If keyword arguments are present, they are first converted to positional
644arguments, as follows. First, a list of unfilled slots is created for the
645formal parameters. If there are N positional arguments, they are placed in the
646first N slots. Next, for each keyword argument, the identifier is used to
647determine the corresponding slot (if the identifier is the same as the first
648formal parameter name, the first slot is used, and so on). If the slot is
649already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
650the argument is placed in the slot, filling it (even if the expression is
651``None``, it fills the slot). When all arguments have been processed, the slots
652that are still unfilled are filled with the corresponding default value from the
653function definition. (Default values are calculated, once, when the function is
654defined; thus, a mutable object such as a list or dictionary used as default
655value will be shared by all calls that don't specify an argument value for the
656corresponding slot; this should usually be avoided.) If there are any unfilled
657slots for which no default value is specified, a :exc:`TypeError` exception is
658raised. Otherwise, the list of filled slots is used as the argument list for
659the call.
660
Georg Brandl495f7b52009-10-27 15:28:25 +0000661.. impl-detail::
Georg Brandl48310cd2009-01-03 21:18:54 +0000662
Georg Brandl495f7b52009-10-27 15:28:25 +0000663 An implementation may provide built-in functions whose positional parameters
664 do not have names, even if they are 'named' for the purpose of documentation,
665 and which therefore cannot be supplied by keyword. In CPython, this is the
Georg Brandl60203b42010-10-06 10:11:56 +0000666 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl495f7b52009-10-27 15:28:25 +0000667 parse their arguments.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000668
Georg Brandl116aa622007-08-15 14:28:22 +0000669If there are more positional arguments than there are formal parameter slots, a
670:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
671``*identifier`` is present; in this case, that formal parameter receives a tuple
672containing the excess positional arguments (or an empty tuple if there were no
673excess positional arguments).
674
675If any keyword argument does not correspond to a formal parameter name, a
676:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
677``**identifier`` is present; in this case, that formal parameter receives a
678dictionary containing the excess keyword arguments (using the keywords as keys
679and the argument values as corresponding values), or a (new) empty dictionary if
680there were no excess keyword arguments.
681
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300682.. index::
683 single: *; in function calls
684
Georg Brandl116aa622007-08-15 14:28:22 +0000685If the syntax ``*expression`` appears in the function call, ``expression`` must
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300686evaluate to an iterable. Elements from this iterable are treated as if they
687were additional positional arguments; if there are positional arguments
Ezio Melotti59256322011-07-30 21:25:22 +0300688*x1*, ..., *xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*,
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300689this is equivalent to a call with M+N positional arguments *x1*, ..., *xN*,
690*y1*, ..., *yM*.
Georg Brandl116aa622007-08-15 14:28:22 +0000691
Benjamin Peterson2d735bc2008-08-19 20:57:10 +0000692A consequence of this is that although the ``*expression`` syntax may appear
693*after* some keyword arguments, it is processed *before* the keyword arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000694(and the ``**expression`` argument, if any -- see below). So::
695
696 >>> def f(a, b):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000697 ... print(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000698 ...
699 >>> f(b=1, *(2,))
700 2 1
701 >>> f(a=1, *(2,))
702 Traceback (most recent call last):
703 File "<stdin>", line 1, in ?
704 TypeError: f() got multiple values for keyword argument 'a'
705 >>> f(1, *(2,))
706 1 2
707
708It is unusual for both keyword arguments and the ``*expression`` syntax to be
709used in the same call, so in practice this confusion does not arise.
710
Eli Bendersky7bd081c2011-07-30 07:05:16 +0300711.. index::
712 single: **; in function calls
713
Georg Brandl116aa622007-08-15 14:28:22 +0000714If the syntax ``**expression`` appears in the function call, ``expression`` must
715evaluate to a mapping, the contents of which are treated as additional keyword
716arguments. In the case of a keyword appearing in both ``expression`` and as an
717explicit keyword argument, a :exc:`TypeError` exception is raised.
718
719Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
720used as positional argument slots or as keyword argument names.
721
722A call always returns some value, possibly ``None``, unless it raises an
723exception. How this value is computed depends on the type of the callable
724object.
725
726If it is---
727
728a user-defined function:
729 .. index::
730 pair: function; call
731 triple: user-defined; function; call
732 object: user-defined function
733 object: function
734
735 The code block for the function is executed, passing it the argument list. The
736 first thing the code block will do is bind the formal parameters to the
737 arguments; this is described in section :ref:`function`. When the code block
738 executes a :keyword:`return` statement, this specifies the return value of the
739 function call.
740
741a built-in function or method:
742 .. index::
743 pair: function; call
744 pair: built-in function; call
745 pair: method; call
746 pair: built-in method; call
747 object: built-in method
748 object: built-in function
749 object: method
750 object: function
751
752 The result is up to the interpreter; see :ref:`built-in-funcs` for the
753 descriptions of built-in functions and methods.
754
755a class object:
756 .. index::
757 object: class
758 pair: class object; call
759
760 A new instance of that class is returned.
761
762a class instance method:
763 .. index::
764 object: class instance
765 object: instance
766 pair: class instance; call
767
768 The corresponding user-defined function is called, with an argument list that is
769 one longer than the argument list of the call: the instance becomes the first
770 argument.
771
772a class instance:
773 .. index::
774 pair: instance; call
775 single: __call__() (object method)
776
777 The class must define a :meth:`__call__` method; the effect is then the same as
778 if that method was called.
779
780
781.. _power:
782
783The power operator
784==================
785
786The power operator binds more tightly than unary operators on its left; it binds
787less tightly than unary operators on its right. The syntax is:
788
789.. productionlist::
790 power: `primary` ["**" `u_expr`]
791
792Thus, in an unparenthesized sequence of power and unary operators, the operators
793are evaluated from right to left (this does not constrain the evaluation order
Guido van Rossum04110fb2007-08-24 16:32:05 +0000794for the operands): ``-1**2`` results in ``-1``.
Georg Brandl116aa622007-08-15 14:28:22 +0000795
796The power operator has the same semantics as the built-in :func:`pow` function,
797when called with two arguments: it yields its left argument raised to the power
798of its right argument. The numeric arguments are first converted to a common
Georg Brandl96593ed2007-09-07 14:15:41 +0000799type, and the result is of that type.
Georg Brandl116aa622007-08-15 14:28:22 +0000800
Georg Brandl96593ed2007-09-07 14:15:41 +0000801For int operands, the result has the same type as the operands unless the second
802argument is negative; in that case, all arguments are converted to float and a
803float result is delivered. For example, ``10**2`` returns ``100``, but
804``10**-2`` returns ``0.01``.
Georg Brandl116aa622007-08-15 14:28:22 +0000805
806Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Christian Heimes072c0f12008-01-03 23:01:04 +0000807Raising a negative number to a fractional power results in a :class:`complex`
Christian Heimesfaf2f632008-01-06 16:59:19 +0000808number. (In earlier versions it raised a :exc:`ValueError`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000809
810
811.. _unary:
812
Benjamin Petersonba01dd92009-02-20 04:02:38 +0000813Unary arithmetic and bitwise operations
814=======================================
Georg Brandl116aa622007-08-15 14:28:22 +0000815
816.. index::
817 triple: unary; arithmetic; operation
Christian Heimesfaf2f632008-01-06 16:59:19 +0000818 triple: unary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000819
Benjamin Petersonba01dd92009-02-20 04:02:38 +0000820All unary arithmetic and bitwise operations have the same priority:
Georg Brandl116aa622007-08-15 14:28:22 +0000821
822.. productionlist::
823 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
824
825.. index::
826 single: negation
827 single: minus
828
829The unary ``-`` (minus) operator yields the negation of its numeric argument.
830
831.. index:: single: plus
832
833The unary ``+`` (plus) operator yields its numeric argument unchanged.
834
835.. index:: single: inversion
836
Christian Heimesfaf2f632008-01-06 16:59:19 +0000837
Georg Brandl95817b32008-05-11 14:30:18 +0000838The unary ``~`` (invert) operator yields the bitwise inversion of its integer
839argument. The bitwise inversion of ``x`` is defined as ``-(x+1)``. It only
840applies to integral numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000841
842.. index:: exception: TypeError
843
844In all three cases, if the argument does not have the proper type, a
845:exc:`TypeError` exception is raised.
846
847
848.. _binary:
849
850Binary arithmetic operations
851============================
852
853.. index:: triple: binary; arithmetic; operation
854
855The binary arithmetic operations have the conventional priority levels. Note
856that some of these operations also apply to certain non-numeric types. Apart
857from the power operator, there are only two levels, one for multiplicative
858operators and one for additive operators:
859
860.. productionlist::
861 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
862 : | `m_expr` "%" `u_expr`
863 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
864
865.. index:: single: multiplication
866
867The ``*`` (multiplication) operator yields the product of its arguments. The
Georg Brandl96593ed2007-09-07 14:15:41 +0000868arguments must either both be numbers, or one argument must be an integer and
869the other must be a sequence. In the former case, the numbers are converted to a
870common type and then multiplied together. In the latter case, sequence
871repetition is performed; a negative repetition factor yields an empty sequence.
Georg Brandl116aa622007-08-15 14:28:22 +0000872
873.. index::
874 exception: ZeroDivisionError
875 single: division
876
877The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
878their arguments. The numeric arguments are first converted to a common type.
Georg Brandl96593ed2007-09-07 14:15:41 +0000879Integer division yields a float, while floor division of integers results in an
880integer; the result is that of mathematical division with the 'floor' function
881applied to the result. Division by zero raises the :exc:`ZeroDivisionError`
882exception.
Georg Brandl116aa622007-08-15 14:28:22 +0000883
884.. index:: single: modulo
885
886The ``%`` (modulo) operator yields the remainder from the division of the first
887argument by the second. The numeric arguments are first converted to a common
888type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
889arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
890(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
891result with the same sign as its second operand (or zero); the absolute value of
892the result is strictly smaller than the absolute value of the second operand
893[#]_.
894
Georg Brandl96593ed2007-09-07 14:15:41 +0000895The floor division and modulo operators are connected by the following
896identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also
897connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y,
898x%y)``. [#]_.
Georg Brandl116aa622007-08-15 14:28:22 +0000899
900In addition to performing the modulo operation on numbers, the ``%`` operator is
Georg Brandl96593ed2007-09-07 14:15:41 +0000901also overloaded by string objects to perform old-style string formatting (also
902known as interpolation). The syntax for string formatting is described in the
Georg Brandl4b491312007-08-31 09:22:56 +0000903Python Library Reference, section :ref:`old-string-formatting`.
Georg Brandl116aa622007-08-15 14:28:22 +0000904
905The floor division operator, the modulo operator, and the :func:`divmod`
Georg Brandl96593ed2007-09-07 14:15:41 +0000906function are not defined for complex numbers. Instead, convert to a floating
907point number using the :func:`abs` function if appropriate.
Georg Brandl116aa622007-08-15 14:28:22 +0000908
909.. index:: single: addition
910
Georg Brandl96593ed2007-09-07 14:15:41 +0000911The ``+`` (addition) operator yields the sum of its arguments. The arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000912must either both be numbers or both sequences of the same type. In the former
913case, the numbers are converted to a common type and then added together. In
914the latter case, the sequences are concatenated.
915
916.. index:: single: subtraction
917
918The ``-`` (subtraction) operator yields the difference of its arguments. The
919numeric arguments are first converted to a common type.
920
921
922.. _shifting:
923
924Shifting operations
925===================
926
927.. index:: pair: shifting; operation
928
929The shifting operations have lower priority than the arithmetic operations:
930
931.. productionlist::
932 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
933
Georg Brandl96593ed2007-09-07 14:15:41 +0000934These operators accept integers as arguments. They shift the first argument to
935the left or right by the number of bits given by the second argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000936
937.. index:: exception: ValueError
938
939A right shift by *n* bits is defined as division by ``pow(2,n)``. A left shift
Georg Brandl96593ed2007-09-07 14:15:41 +0000940by *n* bits is defined as multiplication with ``pow(2,n)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000941
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000942.. note::
943
944 In the current implementation, the right-hand operand is required
Mark Dickinson505add32010-04-06 18:22:06 +0000945 to be at most :attr:`sys.maxsize`. If the right-hand operand is larger than
946 :attr:`sys.maxsize` an :exc:`OverflowError` exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000947
948.. _bitwise:
949
Christian Heimesfaf2f632008-01-06 16:59:19 +0000950Binary bitwise operations
951=========================
Georg Brandl116aa622007-08-15 14:28:22 +0000952
Christian Heimesfaf2f632008-01-06 16:59:19 +0000953.. index:: triple: binary; bitwise; operation
Georg Brandl116aa622007-08-15 14:28:22 +0000954
955Each of the three bitwise operations has a different priority level:
956
957.. productionlist::
958 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
959 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
960 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
961
Christian Heimesfaf2f632008-01-06 16:59:19 +0000962.. index:: pair: bitwise; and
Georg Brandl116aa622007-08-15 14:28:22 +0000963
Georg Brandl96593ed2007-09-07 14:15:41 +0000964The ``&`` operator yields the bitwise AND of its arguments, which must be
965integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000966
967.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +0000968 pair: bitwise; xor
Georg Brandl116aa622007-08-15 14:28:22 +0000969 pair: exclusive; or
970
971The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +0000972must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000973
974.. index::
Christian Heimesfaf2f632008-01-06 16:59:19 +0000975 pair: bitwise; or
Georg Brandl116aa622007-08-15 14:28:22 +0000976 pair: inclusive; or
977
978The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
Georg Brandl96593ed2007-09-07 14:15:41 +0000979must be integers.
Georg Brandl116aa622007-08-15 14:28:22 +0000980
981
982.. _comparisons:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000983.. _is:
Georg Brandl375aec22011-01-15 17:03:02 +0000984.. _is not:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000985.. _in:
Georg Brandl375aec22011-01-15 17:03:02 +0000986.. _not in:
Georg Brandl116aa622007-08-15 14:28:22 +0000987
988Comparisons
989===========
990
991.. index:: single: comparison
992
993.. index:: pair: C; language
994
995Unlike C, all comparison operations in Python have the same priority, which is
996lower than that of any arithmetic, shifting or bitwise operation. Also unlike
997C, expressions like ``a < b < c`` have the interpretation that is conventional
998in mathematics:
999
1000.. productionlist::
1001 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1002 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "!="
1003 : | "is" ["not"] | ["not"] "in"
1004
1005Comparisons yield boolean values: ``True`` or ``False``.
1006
1007.. index:: pair: chaining; comparisons
1008
1009Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1010``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1011cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1012
Guido van Rossum04110fb2007-08-24 16:32:05 +00001013Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1014*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1015to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1016evaluated at most once.
Georg Brandl116aa622007-08-15 14:28:22 +00001017
Guido van Rossum04110fb2007-08-24 16:32:05 +00001018Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl116aa622007-08-15 14:28:22 +00001019*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1020pretty).
1021
1022The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1023values of two objects. The objects need not have the same type. If both are
Georg Brandl9609cea2008-09-09 19:31:57 +00001024numbers, they are converted to a common type. Otherwise, the ``==`` and ``!=``
1025operators *always* consider objects of different types to be unequal, while the
1026``<``, ``>``, ``>=`` and ``<=`` operators raise a :exc:`TypeError` when
1027comparing objects of different types that do not implement these operators for
1028the given pair of types. You can control comparison behavior of objects of
Georg Brandl22b34312009-07-26 14:54:51 +00001029non-built-in types by defining rich comparison methods like :meth:`__gt__`,
Georg Brandl9609cea2008-09-09 19:31:57 +00001030described in section :ref:`customization`.
Georg Brandl116aa622007-08-15 14:28:22 +00001031
1032Comparison of objects of the same type depends on the type:
1033
1034* Numbers are compared arithmetically.
1035
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001036* The values :const:`float('NaN')` and :const:`Decimal('NaN')` are special.
1037 The are identical to themselves, ``x is x`` but are not equal to themselves,
1038 ``x != x``. Additionally, comparing any value to a not-a-number value
1039 will return ``False``. For example, both ``3 < float('NaN')`` and
1040 ``float('NaN') < 3`` will return ``False``.
1041
Georg Brandl96593ed2007-09-07 14:15:41 +00001042* Bytes objects are compared lexicographically using the numeric values of their
1043 elements.
Georg Brandl4b491312007-08-31 09:22:56 +00001044
Georg Brandl116aa622007-08-15 14:28:22 +00001045* Strings are compared lexicographically using the numeric equivalents (the
Georg Brandl96593ed2007-09-07 14:15:41 +00001046 result of the built-in function :func:`ord`) of their characters. [#]_ String
1047 and bytes object can't be compared!
Georg Brandl116aa622007-08-15 14:28:22 +00001048
1049* Tuples and lists are compared lexicographically using comparison of
1050 corresponding elements. This means that to compare equal, each element must
1051 compare equal and the two sequences must be of the same type and have the same
1052 length.
1053
1054 If not equal, the sequences are ordered the same as their first differing
Mark Dickinsonc48d8342009-02-01 14:18:10 +00001055 elements. For example, ``[1,2,x] <= [1,2,y]`` has the same value as
1056 ``x <= y``. If the corresponding element does not exist, the shorter
Georg Brandl96593ed2007-09-07 14:15:41 +00001057 sequence is ordered first (for example, ``[1,2] < [1,2,3]``).
Georg Brandl116aa622007-08-15 14:28:22 +00001058
Senthil Kumaran07367672010-07-14 20:30:02 +00001059* Mappings (dictionaries) compare equal if and only if they have the same
1060 ``(key, value)`` pairs. Order comparisons ``('<', '<=', '>=', '>')``
1061 raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001062
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001063* Sets and frozensets define comparison operators to mean subset and superset
1064 tests. Those relations do not define total orderings (the two sets ``{1,2}``
1065 and {2,3} are not equal, nor subsets of one another, nor supersets of one
1066 another). Accordingly, sets are not appropriate arguments for functions
1067 which depend on total ordering. For example, :func:`min`, :func:`max`, and
1068 :func:`sorted` produce undefined results given a list of sets as inputs.
1069
Georg Brandl22b34312009-07-26 14:54:51 +00001070* Most other objects of built-in types compare unequal unless they are the same
Georg Brandl116aa622007-08-15 14:28:22 +00001071 object; the choice whether one object is considered smaller or larger than
1072 another one is made arbitrarily but consistently within one execution of a
1073 program.
1074
Georg Brandl4614cc42012-10-06 13:48:39 +02001075Comparison of objects of the differing types depends on whether either of the
1076types provide explicit support for the comparison. Most numeric types can be
1077compared with one another. When cross-type comparison is not supported, the
1078comparison method returns ``NotImplemented``.
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001079
Georg Brandl495f7b52009-10-27 15:28:25 +00001080.. _membership-test-details:
1081
Georg Brandl96593ed2007-09-07 14:15:41 +00001082The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in
1083s`` evaluates to true if *x* is a member of *s*, and false otherwise. ``x not
1084in s`` returns the negation of ``x in s``. All built-in sequences and set types
1085support this as well as dictionary, for which :keyword:`in` tests whether a the
Raymond Hettingera2a08fb2008-11-17 22:55:16 +00001086dictionary has a given key. For container types such as list, tuple, set,
Raymond Hettinger0cc818f2008-11-21 10:40:51 +00001087frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
Stefan Krahc8bdc012010-04-01 10:34:09 +00001088to ``any(x is e or x == e for e in y)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001089
Georg Brandl4b491312007-08-31 09:22:56 +00001090For the string and bytes types, ``x in y`` is true if and only if *x* is a
1091substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are
1092always considered to be a substring of any other string, so ``"" in "abc"`` will
1093return ``True``.
Georg Brandl116aa622007-08-15 14:28:22 +00001094
Georg Brandl116aa622007-08-15 14:28:22 +00001095For user-defined classes which define the :meth:`__contains__` method, ``x in
1096y`` is true if and only if ``y.__contains__(x)`` is true.
1097
Georg Brandl495f7b52009-10-27 15:28:25 +00001098For user-defined classes which do not define :meth:`__contains__` but do define
1099:meth:`__iter__`, ``x in y`` is true if some value ``z`` with ``x == z`` is
1100produced while iterating over ``y``. If an exception is raised during the
1101iteration, it is as if :keyword:`in` raised that exception.
1102
1103Lastly, the old-style iteration protocol is tried: if a class defines
Georg Brandl116aa622007-08-15 14:28:22 +00001104:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1105integer index *i* such that ``x == y[i]``, and all lower integer indices do not
Georg Brandl96593ed2007-09-07 14:15:41 +00001106raise :exc:`IndexError` exception. (If any other exception is raised, it is as
Georg Brandl116aa622007-08-15 14:28:22 +00001107if :keyword:`in` raised that exception).
1108
1109.. index::
1110 operator: in
1111 operator: not in
1112 pair: membership; test
1113 object: sequence
1114
1115The operator :keyword:`not in` is defined to have the inverse true value of
1116:keyword:`in`.
1117
1118.. index::
1119 operator: is
1120 operator: is not
1121 pair: identity; test
1122
1123The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1124is 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 +00001125yields the inverse truth value. [#]_
Georg Brandl116aa622007-08-15 14:28:22 +00001126
1127
1128.. _booleans:
Christian Heimes5b5e81c2007-12-31 16:14:33 +00001129.. _and:
1130.. _or:
1131.. _not:
Georg Brandl116aa622007-08-15 14:28:22 +00001132
1133Boolean operations
1134==================
1135
1136.. index::
1137 pair: Conditional; expression
1138 pair: Boolean; operation
1139
Georg Brandl116aa622007-08-15 14:28:22 +00001140.. productionlist::
Georg Brandl116aa622007-08-15 14:28:22 +00001141 or_test: `and_test` | `or_test` "or" `and_test`
1142 and_test: `not_test` | `and_test` "and" `not_test`
1143 not_test: `comparison` | "not" `not_test`
1144
1145In the context of Boolean operations, and also when expressions are used by
1146control flow statements, the following values are interpreted as false:
1147``False``, ``None``, numeric zero of all types, and empty strings and containers
1148(including strings, tuples, lists, dictionaries, sets and frozensets). All
Georg Brandl96593ed2007-09-07 14:15:41 +00001149other values are interpreted as true. User-defined objects can customize their
1150truth value by providing a :meth:`__bool__` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001151
1152.. index:: operator: not
1153
1154The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1155otherwise.
1156
Georg Brandl116aa622007-08-15 14:28:22 +00001157.. index:: operator: and
1158
1159The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1160returned; otherwise, *y* is evaluated and the resulting value is returned.
1161
1162.. index:: operator: or
1163
1164The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1165returned; otherwise, *y* is evaluated and the resulting value is returned.
1166
1167(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1168they return to ``False`` and ``True``, but rather return the last evaluated
Georg Brandl96593ed2007-09-07 14:15:41 +00001169argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Georg Brandl116aa622007-08-15 14:28:22 +00001170replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1171the desired value. Because :keyword:`not` has to invent a value anyway, it does
1172not bother to return a value of the same type as its argument, so e.g., ``not
1173'foo'`` yields ``False``, not ``''``.)
1174
1175
Alexander Belopolsky50ba19e2010-12-15 19:47:37 +00001176Conditional expressions
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001177=======================
1178
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001179.. index::
1180 pair: conditional; expression
1181 pair: ternary; operator
1182
1183.. productionlist::
1184 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1185 expression: `conditional_expression` | `lambda_form`
1186 expression_nocond: `or_test` | `lambda_form_nocond`
1187
1188Conditional expressions (sometimes called a "ternary operator") have the lowest
1189priority of all Python operations.
1190
1191The expression ``x if C else y`` first evaluates the condition, *C* (*not* *x*);
1192if *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
1193evaluated and its value is returned.
1194
1195See :pep:`308` for more details about conditional expressions.
1196
1197
Georg Brandl116aa622007-08-15 14:28:22 +00001198.. _lambdas:
Georg Brandlc4f8b242009-04-10 08:17:21 +00001199.. _lambda:
Georg Brandl116aa622007-08-15 14:28:22 +00001200
1201Lambdas
1202=======
1203
1204.. index::
1205 pair: lambda; expression
1206 pair: lambda; form
1207 pair: anonymous; function
1208
1209.. productionlist::
1210 lambda_form: "lambda" [`parameter_list`]: `expression`
Georg Brandl96593ed2007-09-07 14:15:41 +00001211 lambda_form_nocond: "lambda" [`parameter_list`]: `expression_nocond`
Georg Brandl116aa622007-08-15 14:28:22 +00001212
1213Lambda forms (lambda expressions) have the same syntactic position as
1214expressions. They are a shorthand to create anonymous functions; the expression
1215``lambda arguments: expression`` yields a function object. The unnamed object
1216behaves like a function object defined with ::
1217
Georg Brandl96593ed2007-09-07 14:15:41 +00001218 def <lambda>(arguments):
Georg Brandl116aa622007-08-15 14:28:22 +00001219 return expression
1220
1221See section :ref:`function` for the syntax of parameter lists. Note that
1222functions created with lambda forms cannot contain statements or annotations.
1223
Georg Brandl116aa622007-08-15 14:28:22 +00001224
1225.. _exprlists:
1226
1227Expression lists
1228================
1229
1230.. index:: pair: expression; list
1231
1232.. productionlist::
1233 expression_list: `expression` ( "," `expression` )* [","]
1234
1235.. index:: object: tuple
1236
1237An expression list containing at least one comma yields a tuple. The length of
1238the tuple is the number of expressions in the list. The expressions are
1239evaluated from left to right.
1240
1241.. index:: pair: trailing; comma
1242
1243The trailing comma is required only to create a single tuple (a.k.a. a
1244*singleton*); it is optional in all other cases. A single expression without a
1245trailing comma doesn't create a tuple, but rather yields the value of that
1246expression. (To create an empty tuple, use an empty pair of parentheses:
1247``()``.)
1248
1249
1250.. _evalorder:
1251
1252Evaluation order
1253================
1254
1255.. index:: pair: evaluation; order
1256
Georg Brandl96593ed2007-09-07 14:15:41 +00001257Python evaluates expressions from left to right. Notice that while evaluating
1258an assignment, the right-hand side is evaluated before the left-hand side.
Georg Brandl116aa622007-08-15 14:28:22 +00001259
1260In the following lines, expressions will be evaluated in the arithmetic order of
1261their suffixes::
1262
1263 expr1, expr2, expr3, expr4
1264 (expr1, expr2, expr3, expr4)
1265 {expr1: expr2, expr3: expr4}
1266 expr1 + expr2 * (expr3 - expr4)
Georg Brandl734e2682008-08-12 08:18:18 +00001267 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl116aa622007-08-15 14:28:22 +00001268 expr3, expr4 = expr1, expr2
1269
1270
1271.. _operator-summary:
1272
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001273Operator precedence
1274===================
Georg Brandl116aa622007-08-15 14:28:22 +00001275
1276.. index:: pair: operator; precedence
1277
1278The following table summarizes the operator precedences in Python, from lowest
Georg Brandl96593ed2007-09-07 14:15:41 +00001279precedence (least binding) to highest precedence (most binding). Operators in
Georg Brandl116aa622007-08-15 14:28:22 +00001280the same box have the same precedence. Unless the syntax is explicitly given,
1281operators are binary. Operators in the same box group left to right (except for
1282comparisons, including tests, which all have the same precedence and chain from
1283left to right --- see section :ref:`comparisons` --- and exponentiation, which
1284groups from right to left).
1285
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001286
1287+-----------------------------------------------+-------------------------------------+
1288| Operator | Description |
1289+===============================================+=====================================+
1290| :keyword:`lambda` | Lambda expression |
1291+-----------------------------------------------+-------------------------------------+
Georg Brandl93dc9eb2010-03-14 10:56:14 +00001292| :keyword:`if` -- :keyword:`else` | Conditional expression |
1293+-----------------------------------------------+-------------------------------------+
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001294| :keyword:`or` | Boolean OR |
1295+-----------------------------------------------+-------------------------------------+
1296| :keyword:`and` | Boolean AND |
1297+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001298| :keyword:`not` ``x`` | Boolean NOT |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001299+-----------------------------------------------+-------------------------------------+
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001300| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001301| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests, |
Georg Brandla5ebc262009-06-03 07:26:22 +00001302| ``<=``, ``>``, ``>=``, ``!=``, ``==`` | |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001303+-----------------------------------------------+-------------------------------------+
1304| ``|`` | Bitwise OR |
1305+-----------------------------------------------+-------------------------------------+
1306| ``^`` | Bitwise XOR |
1307+-----------------------------------------------+-------------------------------------+
1308| ``&`` | Bitwise AND |
1309+-----------------------------------------------+-------------------------------------+
1310| ``<<``, ``>>`` | Shifts |
1311+-----------------------------------------------+-------------------------------------+
1312| ``+``, ``-`` | Addition and subtraction |
1313+-----------------------------------------------+-------------------------------------+
1314| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |
Georg Brandlf1d633c2010-09-20 06:29:01 +00001315| | [#]_ |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001316+-----------------------------------------------+-------------------------------------+
1317| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1318+-----------------------------------------------+-------------------------------------+
1319| ``**`` | Exponentiation [#]_ |
1320+-----------------------------------------------+-------------------------------------+
1321| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1322| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1323+-----------------------------------------------+-------------------------------------+
1324| ``(expressions...)``, | Binding or tuple display, |
1325| ``[expressions...]``, | list display, |
Ezio Melotti9f929bb2012-12-25 15:45:15 +02001326| ``{key: value...}``, | dictionary display, |
Brett Cannon925914f2010-11-21 19:58:24 +00001327| ``{expressions...}`` | set display |
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001328+-----------------------------------------------+-------------------------------------+
1329
Georg Brandl116aa622007-08-15 14:28:22 +00001330
1331.. rubric:: Footnotes
1332
Georg Brandl116aa622007-08-15 14:28:22 +00001333.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1334 true numerically due to roundoff. For example, and assuming a platform on which
1335 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1336 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl063f2372010-12-01 15:32:43 +00001337 1e100``, which is numerically exactly equal to ``1e100``. The function
1338 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl116aa622007-08-15 14:28:22 +00001339 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1340 is more appropriate depends on the application.
1341
1342.. [#] If x is very close to an exact integer multiple of y, it's possible for
Georg Brandl96593ed2007-09-07 14:15:41 +00001343 ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such
Georg Brandl116aa622007-08-15 14:28:22 +00001344 cases, Python returns the latter result, in order to preserve that
1345 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1346
Georg Brandl96593ed2007-09-07 14:15:41 +00001347.. [#] While comparisons between strings make sense at the byte level, they may
1348 be counter-intuitive to users. For example, the strings ``"\u00C7"`` and
1349 ``"\u0327\u0043"`` compare differently, even though they both represent the
Georg Brandlae2dbe22009-03-13 19:04:40 +00001350 same unicode character (LATIN CAPITAL LETTER C WITH CEDILLA). To compare
Georg Brandl9afde1c2007-11-01 20:32:30 +00001351 strings in a human recognizable way, compare using
1352 :func:`unicodedata.normalize`.
Guido van Rossumda27fd22007-08-17 00:24:54 +00001353
Georg Brandl48310cd2009-01-03 21:18:54 +00001354.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Benjamin Peterson41181742008-07-02 20:22:54 +00001355 descriptors, you may notice seemingly unusual behaviour in certain uses of
1356 the :keyword:`is` operator, like those involving comparisons between instance
1357 methods, or constants. Check their documentation for more info.
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001358
Georg Brandl063f2372010-12-01 15:32:43 +00001359.. [#] The ``%`` operator is also used for string formatting; the same
1360 precedence applies.
Georg Brandlf1d633c2010-09-20 06:29:01 +00001361
Benjamin Petersonba01dd92009-02-20 04:02:38 +00001362.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1363 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.