blob: 4b05c374f183f35f8d8670b9bc2e9e919f97e1e7 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2.. _expressions:
3
4***********
5Expressions
6***********
7
8.. index:: single: expression
9
10This chapter explains the meaning of the elements of expressions in Python.
11
12.. index:: single: BNF
13
14**Syntax Notes:** In this and the following chapters, extended BNF notation will
15be used to describe syntax, not lexical analysis. When (one alternative of) a
16syntax rule has the form
17
18.. productionlist:: *
19 name: `othername`
20
21.. index:: single: syntax
22
23and no semantics are given, the semantics of this form of ``name`` are the same
24as for ``othername``.
25
26
27.. _conversions:
28
29Arithmetic conversions
30======================
31
32.. index:: pair: arithmetic; conversion
33
34When a description of an arithmetic operator below uses the phrase "the numeric
35arguments are converted to a common type," the arguments are coerced using the
36coercion rules listed at :ref:`coercion-rules`. If both arguments are standard
37numeric types, the following coercions are applied:
38
39* If either argument is a complex number, the other is converted to complex;
40
41* otherwise, if either argument is a floating point number, the other is
42 converted to floating point;
43
44* otherwise, if either argument is a long integer, the other is converted to
45 long integer;
46
47* otherwise, both must be plain integers and no conversion is necessary.
48
49Some additional rules apply for certain operators (e.g., a string left argument
50to the '%' operator). Extensions can define their own coercions.
51
52
53.. _atoms:
54
55Atoms
56=====
57
58.. index:: single: atom
59
60Atoms are the most basic elements of expressions. The simplest atoms are
61identifiers or literals. Forms enclosed in reverse quotes or in parentheses,
62brackets or braces are also categorized syntactically as atoms. The syntax for
63atoms is:
64
65.. productionlist::
66 atom: `identifier` | `literal` | `enclosure`
67 enclosure: `parenth_form` | `list_display`
Alexandre Vassalottiee936a22010-01-09 23:35:54 +000068 : | `generator_expression` | `dict_display` | `set_display`
Georg Brandl8ec7f652007-08-15 14:28:01 +000069 : | `string_conversion` | `yield_atom`
70
71
72.. _atom-identifiers:
73
74Identifiers (Names)
75-------------------
76
77.. index::
78 single: name
79 single: identifier
80
81An identifier occurring as an atom is a name. See section :ref:`identifiers`
82for lexical definition and section :ref:`naming` for documentation of naming and
83binding.
84
85.. index:: exception: NameError
86
87When the name is bound to an object, evaluation of the atom yields that object.
88When a name is not bound, an attempt to evaluate it raises a :exc:`NameError`
89exception.
90
91.. index::
92 pair: name; mangling
93 pair: private; names
94
95**Private name mangling:** When an identifier that textually occurs in a class
96definition begins with two or more underscore characters and does not end in two
97or more underscores, it is considered a :dfn:`private name` of that class.
98Private names are transformed to a longer form before code is generated for
Georg Brandl7a48a8b2013-04-14 10:13:42 +020099them. The transformation inserts the class name, with leading underscores
100removed and a single underscore inserted, in front of the name. For example,
101the identifier ``__spam`` occurring in a class named ``Ham`` will be transformed
102to ``_Ham__spam``. This transformation is independent of the syntactical
103context in which the identifier is used. If the transformed name is extremely
104long (longer than 255 characters), implementation defined truncation may happen.
105If the class name consists only of underscores, no transformation is done.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000106
Georg Brandl8ec7f652007-08-15 14:28:01 +0000107
108
109.. _atom-literals:
110
111Literals
112--------
113
114.. index:: single: literal
115
116Python supports string literals and various numeric literals:
117
118.. productionlist::
119 literal: `stringliteral` | `integer` | `longinteger`
120 : | `floatnumber` | `imagnumber`
121
122Evaluation of a literal yields an object of the given type (string, integer,
123long integer, floating point number, complex number) with the given value. The
124value may be approximated in the case of floating point and imaginary (complex)
125literals. See section :ref:`literals` for details.
126
127.. index::
128 triple: immutable; data; type
129 pair: immutable; object
130
131All literals correspond to immutable data types, and hence the object's identity
132is less important than its value. Multiple evaluations of literals with the
133same value (either the same occurrence in the program text or a different
134occurrence) may obtain the same object or a different object with the same
135value.
136
137
138.. _parenthesized:
139
140Parenthesized forms
141-------------------
142
143.. index:: single: parenthesized form
144
145A parenthesized form is an optional expression list enclosed in parentheses:
146
147.. productionlist::
148 parenth_form: "(" [`expression_list`] ")"
149
150A parenthesized expression list yields whatever that expression list yields: if
151the list contains at least one comma, it yields a tuple; otherwise, it yields
152the single expression that makes up the expression list.
153
154.. index:: pair: empty; tuple
155
156An empty pair of parentheses yields an empty tuple object. Since tuples are
157immutable, the rules for literals apply (i.e., two occurrences of the empty
158tuple may or may not yield the same object).
159
160.. index::
161 single: comma
162 pair: tuple; display
163
164Note that tuples are not formed by the parentheses, but rather by use of the
165comma operator. The exception is the empty tuple, for which parentheses *are*
166required --- allowing unparenthesized "nothing" in expressions would cause
167ambiguities and allow common typos to pass uncaught.
168
169
170.. _lists:
171
172List displays
173-------------
174
175.. index::
176 pair: list; display
177 pair: list; comprehensions
178
179A list display is a possibly empty series of expressions enclosed in square
180brackets:
181
182.. productionlist::
183 list_display: "[" [`expression_list` | `list_comprehension`] "]"
184 list_comprehension: `expression` `list_for`
185 list_for: "for" `target_list` "in" `old_expression_list` [`list_iter`]
186 old_expression_list: `old_expression` [("," `old_expression`)+ [","]]
Georg Brandl38c72032010-03-07 21:12:28 +0000187 old_expression: `or_test` | `old_lambda_form`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000188 list_iter: `list_for` | `list_if`
189 list_if: "if" `old_expression` [`list_iter`]
190
191.. index::
192 pair: list; comprehensions
193 object: list
194 pair: empty; list
195
196A list display yields a new list object. Its contents are specified by
197providing either a list of expressions or a list comprehension. When a
198comma-separated list of expressions is supplied, its elements are evaluated from
199left to right and placed into the list object in that order. When a list
200comprehension is supplied, it consists of a single expression followed by at
201least one :keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if`
202clauses. In this case, the elements of the new list are those that would be
203produced by considering each of the :keyword:`for` or :keyword:`if` clauses a
204block, nesting from left to right, and evaluating the expression to produce a
205list element each time the innermost block is reached [#]_.
206
207
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000208.. _comprehensions:
209
210Displays for sets and dictionaries
211----------------------------------
212
213For constructing a set or a dictionary Python provides special syntax
214called "displays", each of them in two flavors:
215
216* either the container contents are listed explicitly, or
217
218* they are computed via a set of looping and filtering instructions, called a
219 :dfn:`comprehension`.
220
221Common syntax elements for comprehensions are:
222
223.. productionlist::
224 comprehension: `expression` `comp_for`
225 comp_for: "for" `target_list` "in" `or_test` [`comp_iter`]
226 comp_iter: `comp_for` | `comp_if`
227 comp_if: "if" `expression_nocond` [`comp_iter`]
228
229The comprehension consists of a single expression followed by at least one
230:keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if` clauses.
231In this case, the elements of the new container are those that would be produced
232by considering each of the :keyword:`for` or :keyword:`if` clauses a block,
233nesting from left to right, and evaluating the expression to produce an element
234each time the innermost block is reached.
235
236Note that the comprehension is executed in a separate scope, so names assigned
237to in the target list don't "leak" in the enclosing scope.
238
239
Georg Brandl8ec7f652007-08-15 14:28:01 +0000240.. _genexpr:
241
242Generator expressions
243---------------------
244
245.. index:: pair: generator; expression
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000246 object: generator
Georg Brandl8ec7f652007-08-15 14:28:01 +0000247
248A generator expression is a compact generator notation in parentheses:
249
250.. productionlist::
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000251 generator_expression: "(" `expression` `comp_for` ")"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000252
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000253A generator expression yields a new generator object. Its syntax is the same as
254for comprehensions, except that it is enclosed in parentheses instead of
255brackets or curly braces.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000256
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000257Variables used in the generator expression are evaluated lazily when the
258:meth:`__next__` method is called for generator object (in the same fashion as
259normal generators). However, the leftmost :keyword:`for` clause is immediately
260evaluated, so that an error produced by it can be seen before any other possible
Georg Brandl8e67ef52008-03-03 21:31:50 +0000261error in the code that handles the generator expression. Subsequent
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000262:keyword:`for` clauses cannot be evaluated immediately since they may depend on
263the previous :keyword:`for` loop. For example: ``(x*y for x in range(10) for y
264in bar(x))``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000265
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000266The parentheses can be omitted on calls with only one argument. See section
Georg Brandl8ec7f652007-08-15 14:28:01 +0000267:ref:`calls` for the detail.
268
Georg Brandl8ec7f652007-08-15 14:28:01 +0000269.. _dict:
270
271Dictionary displays
272-------------------
273
274.. index:: pair: dictionary; display
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000275 key, datum, key/datum pair
276 object: dictionary
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277
278A dictionary display is a possibly empty series of key/datum pairs enclosed in
279curly braces:
280
281.. productionlist::
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000282 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283 key_datum_list: `key_datum` ("," `key_datum`)* [","]
284 key_datum: `expression` ":" `expression`
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000285 dict_comprehension: `expression` ":" `expression` `comp_for`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000286
287A dictionary display yields a new dictionary object.
288
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000289If a comma-separated sequence of key/datum pairs is given, they are evaluated
290from left to right to define the entries of the dictionary: each key object is
291used as a key into the dictionary to store the corresponding datum. This means
292that you can specify the same key multiple times in the key/datum list, and the
293final dictionary's value for that key will be the last one given.
294
295A dict comprehension, in contrast to list and set comprehensions, needs two
296expressions separated with a colon followed by the usual "for" and "if" clauses.
297When the comprehension is run, the resulting key and value elements are inserted
298in the new dictionary in the order they are produced.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000299
300.. index:: pair: immutable; object
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000301 hashable
Georg Brandl8ec7f652007-08-15 14:28:01 +0000302
303Restrictions on the types of the key values are listed earlier in section
Georg Brandl7c3e79f2007-11-02 20:06:17 +0000304:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000305all mutable objects.) Clashes between duplicate keys are not detected; the last
306datum (textually rightmost in the display) stored for a given key value
307prevails.
308
309
Alexandre Vassalottiee936a22010-01-09 23:35:54 +0000310.. _set:
311
312Set displays
313------------
314
315.. index:: pair: set; display
316 object: set
317
318A set display is denoted by curly braces and distinguishable from dictionary
319displays by the lack of colons separating keys and values:
320
321.. productionlist::
322 set_display: "{" (`expression_list` | `comprehension`) "}"
323
324A set display yields a new mutable set object, the contents being specified by
325either a sequence of expressions or a comprehension. When a comma-separated
326list of expressions is supplied, its elements are evaluated from left to right
327and added to the set object. When a comprehension is supplied, the set is
328constructed from the elements resulting from the comprehension.
329
330An empty set cannot be constructed with ``{}``; this literal constructs an empty
331dictionary.
332
333
Georg Brandl8ec7f652007-08-15 14:28:01 +0000334.. _string-conversions:
335
336String conversions
337------------------
338
339.. index::
340 pair: string; conversion
341 pair: reverse; quotes
342 pair: backward; quotes
343 single: back-quotes
344
345A string conversion is an expression list enclosed in reverse (a.k.a. backward)
346quotes:
347
348.. productionlist::
Sandro Tosi73ce5e72011-10-31 19:19:26 +0100349 string_conversion: "`" `expression_list` "`"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000350
351A string conversion evaluates the contained expression list and converts the
352resulting object into a string according to rules specific to its type.
353
354If the object is a string, a number, ``None``, or a tuple, list or dictionary
355containing only objects whose type is one of these, the resulting string is a
356valid Python expression which can be passed to the built-in function
357:func:`eval` to yield an expression with the same value (or an approximation, if
358floating point numbers are involved).
359
360(In particular, converting a string adds quotes around it and converts "funny"
361characters to escape sequences that are safe to print.)
362
363.. index:: object: recursive
364
365Recursive objects (for example, lists or dictionaries that contain a reference
366to themselves, directly or indirectly) use ``...`` to indicate a recursive
367reference, and the result cannot be passed to :func:`eval` to get an equal value
368(:exc:`SyntaxError` will be raised instead).
369
370.. index::
371 builtin: repr
372 builtin: str
373
374The built-in function :func:`repr` performs exactly the same conversion in its
375argument as enclosing it in parentheses and reverse quotes does. The built-in
376function :func:`str` performs a similar but more user-friendly conversion.
377
378
379.. _yieldexpr:
380
381Yield expressions
382-----------------
383
384.. index::
385 keyword: yield
386 pair: yield; expression
387 pair: generator; function
388
389.. productionlist::
390 yield_atom: "(" `yield_expression` ")"
391 yield_expression: "yield" [`expression_list`]
392
393.. versionadded:: 2.5
394
395The :keyword:`yield` expression is only used when defining a generator function,
396and can only be used in the body of a function definition. Using a
397:keyword:`yield` expression in a function definition is sufficient to cause that
398definition to create a generator function instead of a normal function.
399
400When a generator function is called, it returns an iterator known as a
401generator. That generator then controls the execution of a generator function.
402The execution starts when one of the generator's methods is called. At that
403time, the execution proceeds to the first :keyword:`yield` expression, where it
404is suspended again, returning the value of :token:`expression_list` to
405generator's caller. By suspended we mean that all local state is retained,
406including the current bindings of local variables, the instruction pointer, and
407the internal evaluation stack. When the execution is resumed by calling one of
408the generator's methods, the function can proceed exactly as if the
409:keyword:`yield` expression was just another external call. The value of the
410:keyword:`yield` expression after resuming depends on the method which resumed
411the execution.
412
413.. index:: single: coroutine
414
415All of this makes generator functions quite similar to coroutines; they yield
416multiple times, they have more than one entry point and their execution can be
417suspended. The only difference is that a generator function cannot control
418where should the execution continue after it yields; the control is always
Georg Brandl09302282010-10-06 09:32:48 +0000419transferred to the generator's caller.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000420
421.. index:: object: generator
422
R David Murray85307b42012-08-17 20:49:51 -0400423
424Generator-iterator methods
425^^^^^^^^^^^^^^^^^^^^^^^^^^
426
427This subsection describes the methods of a generator iterator. They can
428be used to control the execution of a generator function.
429
430Note that calling any of the generator methods below when the generator
431is already executing raises a :exc:`ValueError` exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000432
433.. index:: exception: StopIteration
434
435
436.. method:: generator.next()
437
438 Starts the execution of a generator function or resumes it at the last executed
439 :keyword:`yield` expression. When a generator function is resumed with a
440 :meth:`next` method, the current :keyword:`yield` expression always evaluates to
441 :const:`None`. The execution then continues to the next :keyword:`yield`
442 expression, where the generator is suspended again, and the value of the
443 :token:`expression_list` is returned to :meth:`next`'s caller. If the generator
444 exits without yielding another value, a :exc:`StopIteration` exception is
445 raised.
446
447
448.. method:: generator.send(value)
449
450 Resumes the execution and "sends" a value into the generator function. The
451 ``value`` argument becomes the result of the current :keyword:`yield`
452 expression. The :meth:`send` method returns the next value yielded by the
453 generator, or raises :exc:`StopIteration` if the generator exits without
454 yielding another value. When :meth:`send` is called to start the generator, it
455 must be called with :const:`None` as the argument, because there is no
Georg Brandl907a7202008-02-22 12:31:45 +0000456 :keyword:`yield` expression that could receive the value.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000457
458
459.. method:: generator.throw(type[, value[, traceback]])
460
461 Raises an exception of type ``type`` at the point where generator was paused,
462 and returns the next value yielded by the generator function. If the generator
463 exits without yielding another value, a :exc:`StopIteration` exception is
464 raised. If the generator function does not catch the passed-in exception, or
465 raises a different exception, then that exception propagates to the caller.
466
467.. index:: exception: GeneratorExit
468
469
470.. method:: generator.close()
471
472 Raises a :exc:`GeneratorExit` at the point where the generator function was
473 paused. If the generator function then raises :exc:`StopIteration` (by exiting
474 normally, or due to already being closed) or :exc:`GeneratorExit` (by not
475 catching the exception), close returns to its caller. If the generator yields a
476 value, a :exc:`RuntimeError` is raised. If the generator raises any other
477 exception, it is propagated to the caller. :meth:`close` does nothing if the
478 generator has already exited due to an exception or normal exit.
479
480Here is a simple example that demonstrates the behavior of generators and
481generator functions::
482
483 >>> def echo(value=None):
484 ... print "Execution starts when 'next()' is called for the first time."
485 ... try:
486 ... while True:
487 ... try:
488 ... value = (yield value)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000489 ... except Exception, e:
490 ... value = e
491 ... finally:
492 ... print "Don't forget to clean up when 'close()' is called."
493 ...
494 >>> generator = echo(1)
495 >>> print generator.next()
496 Execution starts when 'next()' is called for the first time.
497 1
498 >>> print generator.next()
499 None
500 >>> print generator.send(2)
501 2
502 >>> generator.throw(TypeError, "spam")
503 TypeError('spam',)
504 >>> generator.close()
505 Don't forget to clean up when 'close()' is called.
506
507
508.. seealso::
509
510 :pep:`0342` - Coroutines via Enhanced Generators
511 The proposal to enhance the API and syntax of generators, making them usable as
512 simple coroutines.
513
514
515.. _primaries:
516
517Primaries
518=========
519
520.. index:: single: primary
521
522Primaries represent the most tightly bound operations of the language. Their
523syntax is:
524
525.. productionlist::
526 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
527
528
529.. _attribute-references:
530
531Attribute references
532--------------------
533
534.. index:: pair: attribute; reference
535
536An attribute reference is a primary followed by a period and a name:
537
538.. productionlist::
539 attributeref: `primary` "." `identifier`
540
541.. index::
542 exception: AttributeError
543 object: module
544 object: list
545
546The primary must evaluate to an object of a type that supports attribute
547references, e.g., a module, list, or an instance. This object is then asked to
548produce the attribute whose name is the identifier. If this attribute is not
549available, the exception :exc:`AttributeError` is raised. Otherwise, the type
550and value of the object produced is determined by the object. Multiple
551evaluations of the same attribute reference may yield different objects.
552
553
554.. _subscriptions:
555
556Subscriptions
557-------------
558
559.. index:: single: subscription
560
561.. index::
562 object: sequence
563 object: mapping
564 object: string
565 object: tuple
566 object: list
567 object: dictionary
568 pair: sequence; item
569
570A subscription selects an item of a sequence (string, tuple or list) or mapping
571(dictionary) object:
572
573.. productionlist::
574 subscription: `primary` "[" `expression_list` "]"
575
576The primary must evaluate to an object of a sequence or mapping type.
577
578If the primary is a mapping, the expression list must evaluate to an object
579whose value is one of the keys of the mapping, and the subscription selects the
580value in the mapping that corresponds to that key. (The expression list is a
581tuple except if it has exactly one item.)
582
583If the primary is a sequence, the expression (list) must evaluate to a plain
584integer. If this value is negative, the length of the sequence is added to it
585(so that, e.g., ``x[-1]`` selects the last item of ``x``.) The resulting value
586must be a nonnegative integer less than the number of items in the sequence, and
587the subscription selects the item whose index is that value (counting from
588zero).
589
590.. index::
591 single: character
592 pair: string; item
593
594A string's items are characters. A character is not a separate data type but a
595string of exactly one character.
596
597
598.. _slicings:
599
600Slicings
601--------
602
603.. index::
604 single: slicing
605 single: slice
606
607.. index::
608 object: sequence
609 object: string
610 object: tuple
611 object: list
612
613A slicing selects a range of items in a sequence object (e.g., a string, tuple
614or list). Slicings may be used as expressions or as targets in assignment or
615:keyword:`del` statements. The syntax for a slicing:
616
617.. productionlist::
618 slicing: `simple_slicing` | `extended_slicing`
619 simple_slicing: `primary` "[" `short_slice` "]"
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000620 extended_slicing: `primary` "[" `slice_list` "]"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000621 slice_list: `slice_item` ("," `slice_item`)* [","]
622 slice_item: `expression` | `proper_slice` | `ellipsis`
623 proper_slice: `short_slice` | `long_slice`
624 short_slice: [`lower_bound`] ":" [`upper_bound`]
625 long_slice: `short_slice` ":" [`stride`]
626 lower_bound: `expression`
627 upper_bound: `expression`
628 stride: `expression`
629 ellipsis: "..."
630
631.. index:: pair: extended; slicing
632
633There is ambiguity in the formal syntax here: anything that looks like an
634expression list also looks like a slice list, so any subscription can be
635interpreted as a slicing. Rather than further complicating the syntax, this is
636disambiguated by defining that in this case the interpretation as a subscription
637takes priority over the interpretation as a slicing (this is the case if the
638slice list contains no proper slice nor ellipses). Similarly, when the slice
639list has exactly one short slice and no trailing comma, the interpretation as a
640simple slicing takes priority over that as an extended slicing.
641
642The semantics for a simple slicing are as follows. The primary must evaluate to
643a sequence object. The lower and upper bound expressions, if present, must
644evaluate to plain integers; defaults are zero and the ``sys.maxint``,
645respectively. If either bound is negative, the sequence's length is added to
646it. The slicing now selects all items with index *k* such that ``i <= k < j``
647where *i* and *j* are the specified lower and upper bounds. This may be an
648empty sequence. It is not an error if *i* or *j* lie outside the range of valid
649indexes (such items don't exist so they aren't selected).
650
651.. index::
652 single: start (slice object attribute)
653 single: stop (slice object attribute)
654 single: step (slice object attribute)
655
656The semantics for an extended slicing are as follows. The primary must evaluate
657to a mapping object, and it is indexed with a key that is constructed from the
658slice list, as follows. If the slice list contains at least one comma, the key
659is a tuple containing the conversion of the slice items; otherwise, the
660conversion of the lone slice item is the key. The conversion of a slice item
661that is an expression is that expression. The conversion of an ellipsis slice
662item is the built-in ``Ellipsis`` object. The conversion of a proper slice is a
663slice object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and
664:attr:`step` attributes are the values of the expressions given as lower bound,
665upper bound and stride, respectively, substituting ``None`` for missing
666expressions.
667
668
Chris Jerdonekcf4710c2012-12-25 14:50:21 -0800669.. index::
670 object: callable
671 single: call
672 single: argument; call semantics
673
Georg Brandl8ec7f652007-08-15 14:28:01 +0000674.. _calls:
675
676Calls
677-----
678
Chris Jerdonekcf4710c2012-12-25 14:50:21 -0800679A call calls a callable object (e.g., a :term:`function`) with a possibly empty
680series of :term:`arguments <argument>`:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000681
682.. productionlist::
683 call: `primary` "(" [`argument_list` [","]
684 : | `expression` `genexpr_for`] ")"
685 argument_list: `positional_arguments` ["," `keyword_arguments`]
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000686 : ["," "*" `expression`] ["," `keyword_arguments`]
687 : ["," "**" `expression`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000688 : | `keyword_arguments` ["," "*" `expression`]
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000689 : ["," "**" `expression`]
690 : | "*" `expression` ["," "*" `expression`] ["," "**" `expression`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000691 : | "**" `expression`
692 positional_arguments: `expression` ("," `expression`)*
693 keyword_arguments: `keyword_item` ("," `keyword_item`)*
694 keyword_item: `identifier` "=" `expression`
695
696A trailing comma may be present after the positional and keyword arguments but
697does not affect the semantics.
698
Chris Jerdonekcf4710c2012-12-25 14:50:21 -0800699.. index::
700 single: parameter; call semantics
701
Georg Brandl8ec7f652007-08-15 14:28:01 +0000702The primary must evaluate to a callable object (user-defined functions, built-in
703functions, methods of built-in objects, class objects, methods of class
704instances, and certain class instances themselves are callable; extensions may
705define additional callable object types). All argument expressions are
706evaluated before the call is attempted. Please refer to section :ref:`function`
Chris Jerdonekcf4710c2012-12-25 14:50:21 -0800707for the syntax of formal :term:`parameter` lists.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000708
709If keyword arguments are present, they are first converted to positional
710arguments, as follows. First, a list of unfilled slots is created for the
711formal parameters. If there are N positional arguments, they are placed in the
712first N slots. Next, for each keyword argument, the identifier is used to
713determine the corresponding slot (if the identifier is the same as the first
714formal parameter name, the first slot is used, and so on). If the slot is
715already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
716the argument is placed in the slot, filling it (even if the expression is
717``None``, it fills the slot). When all arguments have been processed, the slots
718that are still unfilled are filled with the corresponding default value from the
719function definition. (Default values are calculated, once, when the function is
720defined; thus, a mutable object such as a list or dictionary used as default
721value will be shared by all calls that don't specify an argument value for the
722corresponding slot; this should usually be avoided.) If there are any unfilled
723slots for which no default value is specified, a :exc:`TypeError` exception is
724raised. Otherwise, the list of filled slots is used as the argument list for
725the call.
726
Georg Brandl6c14e582009-10-22 11:48:10 +0000727.. impl-detail::
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000728
Georg Brandl6c14e582009-10-22 11:48:10 +0000729 An implementation may provide built-in functions whose positional parameters
730 do not have names, even if they are 'named' for the purpose of documentation,
731 and which therefore cannot be supplied by keyword. In CPython, this is the
Sandro Tosi98ed08f2012-01-14 16:42:02 +0100732 case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
Georg Brandl6c14e582009-10-22 11:48:10 +0000733 parse their arguments.
Georg Brandlf8770fb2008-04-27 09:39:59 +0000734
Georg Brandl8ec7f652007-08-15 14:28:01 +0000735If there are more positional arguments than there are formal parameter slots, a
736:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
737``*identifier`` is present; in this case, that formal parameter receives a tuple
738containing the excess positional arguments (or an empty tuple if there were no
739excess positional arguments).
740
741If any keyword argument does not correspond to a formal parameter name, a
742:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
743``**identifier`` is present; in this case, that formal parameter receives a
744dictionary containing the excess keyword arguments (using the keywords as keys
745and the argument values as corresponding values), or a (new) empty dictionary if
746there were no excess keyword arguments.
747
Eli Bendersky2cdf3832011-07-29 14:45:08 +0300748.. index::
749 single: *; in function calls
750
Georg Brandl8ec7f652007-08-15 14:28:01 +0000751If the syntax ``*expression`` appears in the function call, ``expression`` must
Eli Bendersky2cdf3832011-07-29 14:45:08 +0300752evaluate to an iterable. Elements from this iterable are treated as if they
753were additional positional arguments; if there are positional arguments
Ezio Melotti4cfdb072011-07-30 21:31:22 +0300754*x1*, ..., *xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*, this
Eli Bendersky2cdf3832011-07-29 14:45:08 +0300755is equivalent to a call with M+N positional arguments *x1*, ..., *xN*, *y1*,
756..., *yM*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000757
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000758A consequence of this is that although the ``*expression`` syntax may appear
759*after* some keyword arguments, it is processed *before* the keyword arguments
Georg Brandl8ec7f652007-08-15 14:28:01 +0000760(and the ``**expression`` argument, if any -- see below). So::
761
762 >>> def f(a, b):
763 ... print a, b
764 ...
765 >>> f(b=1, *(2,))
766 2 1
767 >>> f(a=1, *(2,))
768 Traceback (most recent call last):
769 File "<stdin>", line 1, in ?
770 TypeError: f() got multiple values for keyword argument 'a'
771 >>> f(1, *(2,))
772 1 2
773
774It is unusual for both keyword arguments and the ``*expression`` syntax to be
775used in the same call, so in practice this confusion does not arise.
776
Eli Bendersky2cdf3832011-07-29 14:45:08 +0300777.. index::
778 single: **; in function calls
779
Georg Brandl8ec7f652007-08-15 14:28:01 +0000780If the syntax ``**expression`` appears in the function call, ``expression`` must
781evaluate to a mapping, the contents of which are treated as additional keyword
782arguments. In the case of a keyword appearing in both ``expression`` and as an
783explicit keyword argument, a :exc:`TypeError` exception is raised.
784
785Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
786used as positional argument slots or as keyword argument names. Formal
787parameters using the syntax ``(sublist)`` cannot be used as keyword argument
788names; the outermost sublist corresponds to a single unnamed argument slot, and
789the argument value is assigned to the sublist using the usual tuple assignment
790rules after all other parameter processing is done.
791
792A call always returns some value, possibly ``None``, unless it raises an
793exception. How this value is computed depends on the type of the callable
794object.
795
796If it is---
797
798a user-defined function:
799 .. index::
800 pair: function; call
801 triple: user-defined; function; call
802 object: user-defined function
803 object: function
804
805 The code block for the function is executed, passing it the argument list. The
806 first thing the code block will do is bind the formal parameters to the
807 arguments; this is described in section :ref:`function`. When the code block
808 executes a :keyword:`return` statement, this specifies the return value of the
809 function call.
810
811a built-in function or method:
812 .. index::
813 pair: function; call
814 pair: built-in function; call
815 pair: method; call
816 pair: built-in method; call
817 object: built-in method
818 object: built-in function
819 object: method
820 object: function
821
822 The result is up to the interpreter; see :ref:`built-in-funcs` for the
823 descriptions of built-in functions and methods.
824
825a class object:
826 .. index::
827 object: class
828 pair: class object; call
829
830 A new instance of that class is returned.
831
832a class instance method:
833 .. index::
834 object: class instance
835 object: instance
836 pair: class instance; call
837
838 The corresponding user-defined function is called, with an argument list that is
839 one longer than the argument list of the call: the instance becomes the first
840 argument.
841
842a class instance:
843 .. index::
844 pair: instance; call
845 single: __call__() (object method)
846
847 The class must define a :meth:`__call__` method; the effect is then the same as
848 if that method was called.
849
850
851.. _power:
852
853The power operator
854==================
855
856The power operator binds more tightly than unary operators on its left; it binds
857less tightly than unary operators on its right. The syntax is:
858
859.. productionlist::
860 power: `primary` ["**" `u_expr`]
861
862Thus, in an unparenthesized sequence of power and unary operators, the operators
863are evaluated from right to left (this does not constrain the evaluation order
Georg Brandlff457b12007-08-21 06:07:08 +0000864for the operands): ``-1**2`` results in ``-1``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000865
866The power operator has the same semantics as the built-in :func:`pow` function,
867when called with two arguments: it yields its left argument raised to the power
868of its right argument. The numeric arguments are first converted to a common
869type. The result type is that of the arguments after coercion.
870
871With mixed operand types, the coercion rules for binary arithmetic operators
872apply. For int and long int operands, the result has the same type as the
873operands (after coercion) unless the second argument is negative; in that case,
874all arguments are converted to float and a float result is delivered. For
875example, ``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``. (This last
876feature was added in Python 2.2. In Python 2.1 and before, if both arguments
877were of integer types and the second argument was negative, an exception was
878raised).
879
880Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000881Raising a negative number to a fractional power results in a :exc:`ValueError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000882
883
884.. _unary:
885
Georg Brandle7cb1ce2009-02-19 08:30:06 +0000886Unary arithmetic and bitwise operations
887=======================================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000888
889.. index::
890 triple: unary; arithmetic; operation
Georg Brandlf725b952008-01-05 19:44:22 +0000891 triple: unary; bitwise; operation
Georg Brandl8ec7f652007-08-15 14:28:01 +0000892
Georg Brandle7cb1ce2009-02-19 08:30:06 +0000893All unary arithmetic and bitwise operations have the same priority:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000894
895.. productionlist::
896 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
897
898.. index::
899 single: negation
900 single: minus
901
902The unary ``-`` (minus) operator yields the negation of its numeric argument.
903
904.. index:: single: plus
905
906The unary ``+`` (plus) operator yields its numeric argument unchanged.
907
908.. index:: single: inversion
909
Georg Brandlf725b952008-01-05 19:44:22 +0000910The unary ``~`` (invert) operator yields the bitwise inversion of its plain or
911long integer argument. The bitwise inversion of ``x`` is defined as
Georg Brandl8ec7f652007-08-15 14:28:01 +0000912``-(x+1)``. It only applies to integral numbers.
913
914.. index:: exception: TypeError
915
916In all three cases, if the argument does not have the proper type, a
917:exc:`TypeError` exception is raised.
918
919
920.. _binary:
921
922Binary arithmetic operations
923============================
924
925.. index:: triple: binary; arithmetic; operation
926
927The binary arithmetic operations have the conventional priority levels. Note
928that some of these operations also apply to certain non-numeric types. Apart
929from the power operator, there are only two levels, one for multiplicative
930operators and one for additive operators:
931
932.. productionlist::
933 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
934 : | `m_expr` "%" `u_expr`
935 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
936
937.. index:: single: multiplication
938
939The ``*`` (multiplication) operator yields the product of its arguments. The
940arguments must either both be numbers, or one argument must be an integer (plain
941or long) and the other must be a sequence. In the former case, the numbers are
942converted to a common type and then multiplied together. In the latter case,
943sequence repetition is performed; a negative repetition factor yields an empty
944sequence.
945
946.. index::
947 exception: ZeroDivisionError
948 single: division
949
950The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
951their arguments. The numeric arguments are first converted to a common type.
952Plain or long integer division yields an integer of the same type; the result is
953that of mathematical division with the 'floor' function applied to the result.
954Division by zero raises the :exc:`ZeroDivisionError` exception.
955
956.. index:: single: modulo
957
958The ``%`` (modulo) operator yields the remainder from the division of the first
959argument by the second. The numeric arguments are first converted to a common
960type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
961arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
962(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
963result with the same sign as its second operand (or zero); the absolute value of
964the result is strictly smaller than the absolute value of the second operand
965[#]_.
966
967The integer division and modulo operators are connected by the following
968identity: ``x == (x/y)*y + (x%y)``. Integer division and modulo are also
969connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x/y,
970x%y)``. These identities don't hold for floating point numbers; there similar
971identities hold approximately where ``x/y`` is replaced by ``floor(x/y)`` or
972``floor(x/y) - 1`` [#]_.
973
974In addition to performing the modulo operation on numbers, the ``%`` operator is
975also overloaded by string and unicode objects to perform string formatting (also
976known as interpolation). The syntax for string formatting is described in the
977Python Library Reference, section :ref:`string-formatting`.
978
979.. deprecated:: 2.3
980 The floor division operator, the modulo operator, and the :func:`divmod`
981 function are no longer defined for complex numbers. Instead, convert to a
982 floating point number using the :func:`abs` function if appropriate.
983
984.. index:: single: addition
985
986The ``+`` (addition) operator yields the sum of its arguments. The arguments
987must either both be numbers or both sequences of the same type. In the former
988case, the numbers are converted to a common type and then added together. In
989the latter case, the sequences are concatenated.
990
991.. index:: single: subtraction
992
993The ``-`` (subtraction) operator yields the difference of its arguments. The
994numeric arguments are first converted to a common type.
995
996
997.. _shifting:
998
999Shifting operations
1000===================
1001
1002.. index:: pair: shifting; operation
1003
1004The shifting operations have lower priority than the arithmetic operations:
1005
1006.. productionlist::
1007 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
1008
1009These operators accept plain or long integers as arguments. The arguments are
1010converted to a common type. They shift the first argument to the left or right
1011by the number of bits given by the second argument.
1012
1013.. index:: exception: ValueError
1014
Georg Brandle9135ba2008-05-11 10:55:59 +00001015A right shift by *n* bits is defined as division by ``pow(2, n)``. A left shift
1016by *n* bits is defined as multiplication with ``pow(2, n)``. Negative shift
1017counts raise a :exc:`ValueError` exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001018
Georg Brandlfb120442010-04-06 20:27:59 +00001019.. note::
1020
1021 In the current implementation, the right-hand operand is required
Mark Dickinsona5db4312010-04-06 18:20:11 +00001022 to be at most :attr:`sys.maxsize`. If the right-hand operand is larger than
1023 :attr:`sys.maxsize` an :exc:`OverflowError` exception is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001024
1025.. _bitwise:
1026
Georg Brandlf725b952008-01-05 19:44:22 +00001027Binary bitwise operations
1028=========================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001029
Georg Brandlf725b952008-01-05 19:44:22 +00001030.. index:: triple: binary; bitwise; operation
Georg Brandl8ec7f652007-08-15 14:28:01 +00001031
1032Each of the three bitwise operations has a different priority level:
1033
1034.. productionlist::
1035 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
1036 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1037 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1038
Georg Brandlf725b952008-01-05 19:44:22 +00001039.. index:: pair: bitwise; and
Georg Brandl8ec7f652007-08-15 14:28:01 +00001040
1041The ``&`` operator yields the bitwise AND of its arguments, which must be plain
1042or long integers. The arguments are converted to a common type.
1043
1044.. index::
Georg Brandlf725b952008-01-05 19:44:22 +00001045 pair: bitwise; xor
Georg Brandl8ec7f652007-08-15 14:28:01 +00001046 pair: exclusive; or
1047
1048The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
1049must be plain or long integers. The arguments are converted to a common type.
1050
1051.. index::
Georg Brandlf725b952008-01-05 19:44:22 +00001052 pair: bitwise; or
Georg Brandl8ec7f652007-08-15 14:28:01 +00001053 pair: inclusive; or
1054
1055The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
1056must be plain or long integers. The arguments are converted to a common type.
1057
1058
1059.. _comparisons:
Georg Brandlb19be572007-12-29 10:57:00 +00001060.. _is:
Georg Brandlc86bb002012-01-14 17:06:53 +01001061.. _is not:
Georg Brandlb19be572007-12-29 10:57:00 +00001062.. _in:
Georg Brandlc86bb002012-01-14 17:06:53 +01001063.. _not in:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001064
1065Comparisons
1066===========
1067
1068.. index:: single: comparison
1069
1070.. index:: pair: C; language
1071
1072Unlike C, all comparison operations in Python have the same priority, which is
1073lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1074C, expressions like ``a < b < c`` have the interpretation that is conventional
1075in mathematics:
1076
1077.. productionlist::
1078 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1079 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
1080 : | "is" ["not"] | ["not"] "in"
1081
1082Comparisons yield boolean values: ``True`` or ``False``.
1083
1084.. index:: pair: chaining; comparisons
1085
1086Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1087``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1088cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1089
Georg Brandl32008322007-08-21 06:12:19 +00001090Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1091*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1092to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1093evaluated at most once.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001094
Georg Brandl32008322007-08-21 06:12:19 +00001095Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl8ec7f652007-08-15 14:28:01 +00001096*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1097pretty).
1098
1099The forms ``<>`` and ``!=`` are equivalent; for consistency with C, ``!=`` is
1100preferred; where ``!=`` is mentioned below ``<>`` is also accepted. The ``<>``
1101spelling is considered obsolescent.
1102
1103The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1104values of two objects. The objects need not have the same type. If both are
1105numbers, they are converted to a common type. Otherwise, objects of different
1106types *always* compare unequal, and are ordered consistently but arbitrarily.
Georg Brandld7d4fd72009-07-26 14:37:28 +00001107You can control comparison behavior of objects of non-built-in types by defining
Georg Brandl8ec7f652007-08-15 14:28:01 +00001108a ``__cmp__`` method or rich comparison methods like ``__gt__``, described in
1109section :ref:`specialnames`.
1110
1111(This unusual definition of comparison was used to simplify the definition of
1112operations like sorting and the :keyword:`in` and :keyword:`not in` operators.
1113In the future, the comparison rules for objects of different types are likely to
1114change.)
1115
1116Comparison of objects of the same type depends on the type:
1117
1118* Numbers are compared arithmetically.
1119
1120* Strings are compared lexicographically using the numeric equivalents (the
1121 result of the built-in function :func:`ord`) of their characters. Unicode and
Mark Summerfield216ad332007-08-16 10:09:22 +00001122 8-bit strings are fully interoperable in this behavior. [#]_
Georg Brandl8ec7f652007-08-15 14:28:01 +00001123
1124* Tuples and lists are compared lexicographically using comparison of
1125 corresponding elements. This means that to compare equal, each element must
1126 compare equal and the two sequences must be of the same type and have the same
1127 length.
1128
1129 If not equal, the sequences are ordered the same as their first differing
1130 elements. For example, ``cmp([1,2,x], [1,2,y])`` returns the same as
1131 ``cmp(x,y)``. If the corresponding element does not exist, the shorter sequence
1132 is ordered first (for example, ``[1,2] < [1,2,3]``).
1133
1134* Mappings (dictionaries) compare equal if and only if their sorted (key, value)
1135 lists compare equal. [#]_ Outcomes other than equality are resolved
1136 consistently, but are not otherwise defined. [#]_
1137
Georg Brandld7d4fd72009-07-26 14:37:28 +00001138* Most other objects of built-in types compare unequal unless they are the same
Georg Brandl8ec7f652007-08-15 14:28:01 +00001139 object; the choice whether one object is considered smaller or larger than
1140 another one is made arbitrarily but consistently within one execution of a
1141 program.
1142
Georg Brandl2eee1d42009-10-22 15:00:06 +00001143.. _membership-test-details:
1144
Georg Brandl489343e2008-03-28 12:24:51 +00001145The operators :keyword:`in` and :keyword:`not in` test for collection
1146membership. ``x in s`` evaluates to true if *x* is a member of the collection
1147*s*, and false otherwise. ``x not in s`` returns the negation of ``x in s``.
1148The collection membership test has traditionally been bound to sequences; an
1149object is a member of a collection if the collection is a sequence and contains
1150an element equal to that object. However, it make sense for many other object
1151types to support membership tests without being a sequence. In particular,
1152dictionaries (for keys) and sets support membership testing.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001153
1154For the list and tuple types, ``x in y`` is true if and only if there exists an
1155index *i* such that ``x == y[i]`` is true.
1156
1157For the Unicode and string types, ``x in y`` is true if and only if *x* is a
1158substring of *y*. An equivalent test is ``y.find(x) != -1``. Note, *x* and *y*
1159need not be the same type; consequently, ``u'ab' in 'abc'`` will return
1160``True``. Empty strings are always considered to be a substring of any other
1161string, so ``"" in "abc"`` will return ``True``.
1162
1163.. versionchanged:: 2.3
1164 Previously, *x* was required to be a string of length ``1``.
1165
1166For user-defined classes which define the :meth:`__contains__` method, ``x in
1167y`` is true if and only if ``y.__contains__(x)`` is true.
1168
Georg Brandl2eee1d42009-10-22 15:00:06 +00001169For user-defined classes which do not define :meth:`__contains__` but do define
1170:meth:`__iter__`, ``x in y`` is true if some value ``z`` with ``x == z`` is
1171produced while iterating over ``y``. If an exception is raised during the
1172iteration, it is as if :keyword:`in` raised that exception.
1173
1174Lastly, the old-style iteration protocol is tried: if a class defines
Georg Brandl8ec7f652007-08-15 14:28:01 +00001175:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1176integer index *i* such that ``x == y[i]``, and all lower integer indices do not
1177raise :exc:`IndexError` exception. (If any other exception is raised, it is as
1178if :keyword:`in` raised that exception).
1179
1180.. index::
1181 operator: in
1182 operator: not in
1183 pair: membership; test
1184 object: sequence
1185
1186The operator :keyword:`not in` is defined to have the inverse true value of
1187:keyword:`in`.
1188
1189.. index::
1190 operator: is
1191 operator: is not
1192 pair: identity; test
1193
1194The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1195is y`` is true if and only if *x* and *y* are the same object. ``x is not y``
Georg Brandl3214a012008-07-01 20:50:02 +00001196yields the inverse truth value. [#]_
Georg Brandl8ec7f652007-08-15 14:28:01 +00001197
1198
1199.. _booleans:
Georg Brandlb19be572007-12-29 10:57:00 +00001200.. _and:
1201.. _or:
1202.. _not:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001203
1204Boolean operations
1205==================
1206
1207.. index::
1208 pair: Conditional; expression
1209 pair: Boolean; operation
1210
Georg Brandl8ec7f652007-08-15 14:28:01 +00001211.. productionlist::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001212 or_test: `and_test` | `or_test` "or" `and_test`
1213 and_test: `not_test` | `and_test` "and" `not_test`
1214 not_test: `comparison` | "not" `not_test`
1215
1216In the context of Boolean operations, and also when expressions are used by
1217control flow statements, the following values are interpreted as false:
1218``False``, ``None``, numeric zero of all types, and empty strings and containers
1219(including strings, tuples, lists, dictionaries, sets and frozensets). All
Benjamin Petersonfe7c26d2008-09-23 13:32:46 +00001220other values are interpreted as true. (See the :meth:`~object.__nonzero__`
1221special method for a way to change this.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001222
1223.. index:: operator: not
1224
1225The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1226otherwise.
1227
Georg Brandl8ec7f652007-08-15 14:28:01 +00001228.. index:: operator: and
1229
1230The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1231returned; otherwise, *y* is evaluated and the resulting value is returned.
1232
1233.. index:: operator: or
1234
1235The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1236returned; otherwise, *y* is evaluated and the resulting value is returned.
1237
1238(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1239they return to ``False`` and ``True``, but rather return the last evaluated
1240argument. This is sometimes useful, e.g., if ``s`` is a string that should be
1241replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1242the desired value. Because :keyword:`not` has to invent a value anyway, it does
1243not bother to return a value of the same type as its argument, so e.g., ``not
1244'foo'`` yields ``False``, not ``''``.)
1245
1246
Georg Brandl38c72032010-03-07 21:12:28 +00001247Conditional Expressions
1248=======================
1249
1250.. versionadded:: 2.5
1251
1252.. index::
1253 pair: conditional; expression
1254 pair: ternary; operator
1255
1256.. productionlist::
1257 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1258 expression: `conditional_expression` | `lambda_form`
1259
1260Conditional expressions (sometimes called a "ternary operator") have the lowest
1261priority of all Python operations.
1262
Georg Brandld22557c2010-03-08 16:28:40 +00001263The expression ``x if C else y`` first evaluates the condition, *C* (*not* *x*);
Georg Brandl38c72032010-03-07 21:12:28 +00001264if *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
1265evaluated and its value is returned.
1266
1267See :pep:`308` for more details about conditional expressions.
1268
1269
Georg Brandl8ec7f652007-08-15 14:28:01 +00001270.. _lambdas:
Georg Brandl5623e502009-04-10 08:16:47 +00001271.. _lambda:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001272
1273Lambdas
1274=======
1275
1276.. index::
1277 pair: lambda; expression
1278 pair: lambda; form
1279 pair: anonymous; function
1280
1281.. productionlist::
1282 lambda_form: "lambda" [`parameter_list`]: `expression`
1283 old_lambda_form: "lambda" [`parameter_list`]: `old_expression`
1284
1285Lambda forms (lambda expressions) have the same syntactic position as
1286expressions. They are a shorthand to create anonymous functions; the expression
1287``lambda arguments: expression`` yields a function object. The unnamed object
1288behaves like a function object defined with ::
1289
1290 def name(arguments):
1291 return expression
1292
1293See section :ref:`function` for the syntax of parameter lists. Note that
1294functions created with lambda forms cannot contain statements.
1295
Georg Brandl8ec7f652007-08-15 14:28:01 +00001296
1297.. _exprlists:
1298
1299Expression lists
1300================
1301
1302.. index:: pair: expression; list
1303
1304.. productionlist::
1305 expression_list: `expression` ( "," `expression` )* [","]
1306
1307.. index:: object: tuple
1308
1309An expression list containing at least one comma yields a tuple. The length of
1310the tuple is the number of expressions in the list. The expressions are
1311evaluated from left to right.
1312
1313.. index:: pair: trailing; comma
1314
1315The trailing comma is required only to create a single tuple (a.k.a. a
1316*singleton*); it is optional in all other cases. A single expression without a
1317trailing comma doesn't create a tuple, but rather yields the value of that
1318expression. (To create an empty tuple, use an empty pair of parentheses:
1319``()``.)
1320
1321
1322.. _evalorder:
1323
1324Evaluation order
1325================
1326
1327.. index:: pair: evaluation; order
1328
1329Python evaluates expressions from left to right. Notice that while evaluating an
1330assignment, the right-hand side is evaluated before the left-hand side.
1331
1332In the following lines, expressions will be evaluated in the arithmetic order of
1333their suffixes::
1334
1335 expr1, expr2, expr3, expr4
1336 (expr1, expr2, expr3, expr4)
1337 {expr1: expr2, expr3: expr4}
1338 expr1 + expr2 * (expr3 - expr4)
Georg Brandl463f39d2008-08-08 06:42:20 +00001339 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001340 expr3, expr4 = expr1, expr2
1341
1342
1343.. _operator-summary:
1344
Ezio Melotti4268b3a2012-12-25 15:45:15 +02001345Operator precedence
1346===================
Georg Brandl8ec7f652007-08-15 14:28:01 +00001347
1348.. index:: pair: operator; precedence
1349
1350The following table summarizes the operator precedences in Python, from lowest
1351precedence (least binding) to highest precedence (most binding). Operators in
1352the same box have the same precedence. Unless the syntax is explicitly given,
1353operators are binary. Operators in the same box group left to right (except for
1354comparisons, including tests, which all have the same precedence and chain from
1355left to right --- see section :ref:`comparisons` --- and exponentiation, which
1356groups from right to left).
1357
1358+-----------------------------------------------+-------------------------------------+
1359| Operator | Description |
1360+===============================================+=====================================+
1361| :keyword:`lambda` | Lambda expression |
1362+-----------------------------------------------+-------------------------------------+
Georg Brandl38c72032010-03-07 21:12:28 +00001363| :keyword:`if` -- :keyword:`else` | Conditional expression |
1364+-----------------------------------------------+-------------------------------------+
Georg Brandl8ec7f652007-08-15 14:28:01 +00001365| :keyword:`or` | Boolean OR |
1366+-----------------------------------------------+-------------------------------------+
1367| :keyword:`and` | Boolean AND |
1368+-----------------------------------------------+-------------------------------------+
Ezio Melotti4268b3a2012-12-25 15:45:15 +02001369| :keyword:`not` ``x`` | Boolean NOT |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001370+-----------------------------------------------+-------------------------------------+
Ezio Melotti4268b3a2012-12-25 15:45:15 +02001371| :keyword:`in`, :keyword:`not in`, | Comparisons, including membership |
Georg Brandl44ea77b2013-03-28 13:28:44 +01001372| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests |
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001373| ``<=``, ``>``, ``>=``, ``<>``, ``!=``, ``==`` | |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001374+-----------------------------------------------+-------------------------------------+
1375| ``|`` | Bitwise OR |
1376+-----------------------------------------------+-------------------------------------+
1377| ``^`` | Bitwise XOR |
1378+-----------------------------------------------+-------------------------------------+
1379| ``&`` | Bitwise AND |
1380+-----------------------------------------------+-------------------------------------+
1381| ``<<``, ``>>`` | Shifts |
1382+-----------------------------------------------+-------------------------------------+
1383| ``+``, ``-`` | Addition and subtraction |
1384+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001385| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |
Georg Brandl21946af2010-10-06 09:28:45 +00001386| | [#]_ |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001387+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001388| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001389+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001390| ``**`` | Exponentiation [#]_ |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001391+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001392| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1393| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001394+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001395| ``(expressions...)``, | Binding or tuple display, |
1396| ``[expressions...]``, | list display, |
Ezio Melotti4268b3a2012-12-25 15:45:15 +02001397| ``{key: value...}``, | dictionary display, |
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001398| ```expressions...``` | string conversion |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001399+-----------------------------------------------+-------------------------------------+
1400
1401.. rubric:: Footnotes
1402
Martin v. Löwis0b667312008-05-23 19:33:13 +00001403.. [#] In Python 2.3 and later releases, a list comprehension "leaks" the control
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001404 variables of each ``for`` it contains into the containing scope. However, this
Ezio Melotti510ff542012-05-03 19:21:40 +03001405 behavior is deprecated, and relying on it will not work in Python 3.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001406
1407.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1408 true numerically due to roundoff. For example, and assuming a platform on which
1409 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1410 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
Georg Brandl52f83952011-02-25 10:39:23 +00001411 1e100``, which is numerically exactly equal to ``1e100``. The function
1412 :func:`math.fmod` returns a result whose sign matches the sign of the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001413 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1414 is more appropriate depends on the application.
1415
1416.. [#] If x is very close to an exact integer multiple of y, it's possible for
1417 ``floor(x/y)`` to be one larger than ``(x-x%y)/y`` due to rounding. In such
1418 cases, Python returns the latter result, in order to preserve that
1419 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1420
Mark Summerfield216ad332007-08-16 10:09:22 +00001421.. [#] While comparisons between unicode strings make sense at the byte
1422 level, they may be counter-intuitive to users. For example, the
Mark Summerfieldd92e8712007-10-03 08:53:21 +00001423 strings ``u"\u00C7"`` and ``u"\u0043\u0327"`` compare differently,
Mark Summerfield216ad332007-08-16 10:09:22 +00001424 even though they both represent the same unicode character (LATIN
Georg Brandl6eba7792010-04-02 08:51:31 +00001425 CAPITAL LETTER C WITH CEDILLA). To compare strings in a human
Mark Summerfieldd92e8712007-10-03 08:53:21 +00001426 recognizable way, compare using :func:`unicodedata.normalize`.
Mark Summerfield216ad332007-08-16 10:09:22 +00001427
Georg Brandl8ec7f652007-08-15 14:28:01 +00001428.. [#] The implementation computes this efficiently, without constructing lists or
1429 sorting.
1430
1431.. [#] Earlier versions of Python used lexicographic comparison of the sorted (key,
1432 value) lists, but this was very expensive for the common case of comparing for
1433 equality. An even earlier version of Python compared dictionaries by identity
1434 only, but this caused surprises because people expected to be able to test a
1435 dictionary for emptiness by comparing it to ``{}``.
1436
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001437.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Georg Brandl3214a012008-07-01 20:50:02 +00001438 descriptors, you may notice seemingly unusual behaviour in certain uses of
1439 the :keyword:`is` operator, like those involving comparisons between instance
1440 methods, or constants. Check their documentation for more info.
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001441
Georg Brandl52f83952011-02-25 10:39:23 +00001442.. [#] The ``%`` operator is also used for string formatting; the same
1443 precedence applies.
Georg Brandl21946af2010-10-06 09:28:45 +00001444
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001445.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1446 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.