blob: 9761f21dbf63a4e789697bc5776f8b93d4d091c7 [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
99them. The transformation inserts the class name in front of the name, with
100leading underscores removed, and a single underscore inserted in front of the
101class name. For example, the identifier ``__spam`` occurring in a class named
102``Ham`` will be transformed to ``_Ham__spam``. This transformation is
103independent of the syntactical context in which the identifier is used. If the
104transformed name is extremely long (longer than 255 characters), implementation
105defined truncation may happen. If the class name consists only of underscores,
106no transformation is done.
107
Georg Brandl8ec7f652007-08-15 14:28:01 +0000108
109
110.. _atom-literals:
111
112Literals
113--------
114
115.. index:: single: literal
116
117Python supports string literals and various numeric literals:
118
119.. productionlist::
120 literal: `stringliteral` | `integer` | `longinteger`
121 : | `floatnumber` | `imagnumber`
122
123Evaluation of a literal yields an object of the given type (string, integer,
124long integer, floating point number, complex number) with the given value. The
125value may be approximated in the case of floating point and imaginary (complex)
126literals. See section :ref:`literals` for details.
127
128.. index::
129 triple: immutable; data; type
130 pair: immutable; object
131
132All literals correspond to immutable data types, and hence the object's identity
133is less important than its value. Multiple evaluations of literals with the
134same value (either the same occurrence in the program text or a different
135occurrence) may obtain the same object or a different object with the same
136value.
137
138
139.. _parenthesized:
140
141Parenthesized forms
142-------------------
143
144.. index:: single: parenthesized form
145
146A parenthesized form is an optional expression list enclosed in parentheses:
147
148.. productionlist::
149 parenth_form: "(" [`expression_list`] ")"
150
151A parenthesized expression list yields whatever that expression list yields: if
152the list contains at least one comma, it yields a tuple; otherwise, it yields
153the single expression that makes up the expression list.
154
155.. index:: pair: empty; tuple
156
157An empty pair of parentheses yields an empty tuple object. Since tuples are
158immutable, the rules for literals apply (i.e., two occurrences of the empty
159tuple may or may not yield the same object).
160
161.. index::
162 single: comma
163 pair: tuple; display
164
165Note that tuples are not formed by the parentheses, but rather by use of the
166comma operator. The exception is the empty tuple, for which parentheses *are*
167required --- allowing unparenthesized "nothing" in expressions would cause
168ambiguities and allow common typos to pass uncaught.
169
170
171.. _lists:
172
173List displays
174-------------
175
176.. index::
177 pair: list; display
178 pair: list; comprehensions
179
180A list display is a possibly empty series of expressions enclosed in square
181brackets:
182
183.. productionlist::
184 list_display: "[" [`expression_list` | `list_comprehension`] "]"
185 list_comprehension: `expression` `list_for`
186 list_for: "for" `target_list` "in" `old_expression_list` [`list_iter`]
187 old_expression_list: `old_expression` [("," `old_expression`)+ [","]]
188 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
208.. _genexpr:
209
210Generator expressions
211---------------------
212
213.. index:: pair: generator; expression
214
215A generator expression is a compact generator notation in parentheses:
216
217.. productionlist::
218 generator_expression: "(" `expression` `genexpr_for` ")"
219 genexpr_for: "for" `target_list` "in" `or_test` [`genexpr_iter`]
220 genexpr_iter: `genexpr_for` | `genexpr_if`
221 genexpr_if: "if" `old_expression` [`genexpr_iter`]
222
223.. index:: object: generator
224
225A generator expression yields a new generator object. It consists of a single
226expression followed by at least one :keyword:`for` clause and zero or more
227:keyword:`for` or :keyword:`if` clauses. The iterating values of the new
228generator are those that would be produced by considering each of the
229:keyword:`for` or :keyword:`if` clauses a block, nesting from left to right, and
230evaluating the expression to yield a value that is reached the innermost block
231for each iteration.
232
Georg Brandl8e67ef52008-03-03 21:31:50 +0000233Variables used in the generator expression are evaluated lazily in a separate
234scope when the :meth:`next` method is called for the generator object (in the
235same fashion as for normal generators). However, the :keyword:`in` expression
236of the leftmost :keyword:`for` clause is immediately evaluated in the current
237scope so that an error produced by it can be seen before any other possible
238error in the code that handles the generator expression. Subsequent
239:keyword:`for` and :keyword:`if` clauses cannot be evaluated immediately since
240they may depend on the previous :keyword:`for` loop. For example:
241``(x*y for x in range(10) for y in bar(x))``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000242
243The parentheses can be omitted on calls with only one argument. See section
244:ref:`calls` for the detail.
245
246
247.. _dict:
248
249Dictionary displays
250-------------------
251
252.. index:: pair: dictionary; display
253
254.. index::
255 single: key
256 single: datum
257 single: key/datum pair
258
259A dictionary display is a possibly empty series of key/datum pairs enclosed in
260curly braces:
261
262.. productionlist::
263 dict_display: "{" [`key_datum_list`] "}"
264 key_datum_list: `key_datum` ("," `key_datum`)* [","]
265 key_datum: `expression` ":" `expression`
266
267.. index:: object: dictionary
268
269A dictionary display yields a new dictionary object.
270
271The key/datum pairs are evaluated from left to right to define the entries of
272the dictionary: each key object is used as a key into the dictionary to store
273the corresponding datum.
274
275.. index:: pair: immutable; object
276
277Restrictions on the types of the key values are listed earlier in section
Georg Brandl7c3e79f2007-11-02 20:06:17 +0000278:ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
Georg Brandl8ec7f652007-08-15 14:28:01 +0000279all mutable objects.) Clashes between duplicate keys are not detected; the last
280datum (textually rightmost in the display) stored for a given key value
281prevails.
282
283
Alexandre Vassalottiee936a22010-01-09 23:35:54 +0000284.. _set:
285
286Set displays
287------------
288
289.. index:: pair: set; display
290 object: set
291
292A set display is denoted by curly braces and distinguishable from dictionary
293displays by the lack of colons separating keys and values:
294
295.. productionlist::
296 set_display: "{" (`expression_list` | `comprehension`) "}"
297
298A set display yields a new mutable set object, the contents being specified by
299either a sequence of expressions or a comprehension. When a comma-separated
300list of expressions is supplied, its elements are evaluated from left to right
301and added to the set object. When a comprehension is supplied, the set is
302constructed from the elements resulting from the comprehension.
303
304An empty set cannot be constructed with ``{}``; this literal constructs an empty
305dictionary.
306
307
Georg Brandl8ec7f652007-08-15 14:28:01 +0000308.. _string-conversions:
309
310String conversions
311------------------
312
313.. index::
314 pair: string; conversion
315 pair: reverse; quotes
316 pair: backward; quotes
317 single: back-quotes
318
319A string conversion is an expression list enclosed in reverse (a.k.a. backward)
320quotes:
321
322.. productionlist::
323 string_conversion: "'" `expression_list` "'"
324
325A string conversion evaluates the contained expression list and converts the
326resulting object into a string according to rules specific to its type.
327
328If the object is a string, a number, ``None``, or a tuple, list or dictionary
329containing only objects whose type is one of these, the resulting string is a
330valid Python expression which can be passed to the built-in function
331:func:`eval` to yield an expression with the same value (or an approximation, if
332floating point numbers are involved).
333
334(In particular, converting a string adds quotes around it and converts "funny"
335characters to escape sequences that are safe to print.)
336
337.. index:: object: recursive
338
339Recursive objects (for example, lists or dictionaries that contain a reference
340to themselves, directly or indirectly) use ``...`` to indicate a recursive
341reference, and the result cannot be passed to :func:`eval` to get an equal value
342(:exc:`SyntaxError` will be raised instead).
343
344.. index::
345 builtin: repr
346 builtin: str
347
348The built-in function :func:`repr` performs exactly the same conversion in its
349argument as enclosing it in parentheses and reverse quotes does. The built-in
350function :func:`str` performs a similar but more user-friendly conversion.
351
352
353.. _yieldexpr:
354
355Yield expressions
356-----------------
357
358.. index::
359 keyword: yield
360 pair: yield; expression
361 pair: generator; function
362
363.. productionlist::
364 yield_atom: "(" `yield_expression` ")"
365 yield_expression: "yield" [`expression_list`]
366
367.. versionadded:: 2.5
368
369The :keyword:`yield` expression is only used when defining a generator function,
370and can only be used in the body of a function definition. Using a
371:keyword:`yield` expression in a function definition is sufficient to cause that
372definition to create a generator function instead of a normal function.
373
374When a generator function is called, it returns an iterator known as a
375generator. That generator then controls the execution of a generator function.
376The execution starts when one of the generator's methods is called. At that
377time, the execution proceeds to the first :keyword:`yield` expression, where it
378is suspended again, returning the value of :token:`expression_list` to
379generator's caller. By suspended we mean that all local state is retained,
380including the current bindings of local variables, the instruction pointer, and
381the internal evaluation stack. When the execution is resumed by calling one of
382the generator's methods, the function can proceed exactly as if the
383:keyword:`yield` expression was just another external call. The value of the
384:keyword:`yield` expression after resuming depends on the method which resumed
385the execution.
386
387.. index:: single: coroutine
388
389All of this makes generator functions quite similar to coroutines; they yield
390multiple times, they have more than one entry point and their execution can be
391suspended. The only difference is that a generator function cannot control
392where should the execution continue after it yields; the control is always
393transfered to the generator's caller.
394
395.. index:: object: generator
396
397The following generator's methods can be used to control the execution of a
398generator function:
399
400.. index:: exception: StopIteration
401
402
403.. method:: generator.next()
404
405 Starts the execution of a generator function or resumes it at the last executed
406 :keyword:`yield` expression. When a generator function is resumed with a
407 :meth:`next` method, the current :keyword:`yield` expression always evaluates to
408 :const:`None`. The execution then continues to the next :keyword:`yield`
409 expression, where the generator is suspended again, and the value of the
410 :token:`expression_list` is returned to :meth:`next`'s caller. If the generator
411 exits without yielding another value, a :exc:`StopIteration` exception is
412 raised.
413
414
415.. method:: generator.send(value)
416
417 Resumes the execution and "sends" a value into the generator function. The
418 ``value`` argument becomes the result of the current :keyword:`yield`
419 expression. The :meth:`send` method returns the next value yielded by the
420 generator, or raises :exc:`StopIteration` if the generator exits without
421 yielding another value. When :meth:`send` is called to start the generator, it
422 must be called with :const:`None` as the argument, because there is no
Georg Brandl907a7202008-02-22 12:31:45 +0000423 :keyword:`yield` expression that could receive the value.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000424
425
426.. method:: generator.throw(type[, value[, traceback]])
427
428 Raises an exception of type ``type`` at the point where generator was paused,
429 and returns the next value yielded by the generator function. If the generator
430 exits without yielding another value, a :exc:`StopIteration` exception is
431 raised. If the generator function does not catch the passed-in exception, or
432 raises a different exception, then that exception propagates to the caller.
433
434.. index:: exception: GeneratorExit
435
436
437.. method:: generator.close()
438
439 Raises a :exc:`GeneratorExit` at the point where the generator function was
440 paused. If the generator function then raises :exc:`StopIteration` (by exiting
441 normally, or due to already being closed) or :exc:`GeneratorExit` (by not
442 catching the exception), close returns to its caller. If the generator yields a
443 value, a :exc:`RuntimeError` is raised. If the generator raises any other
444 exception, it is propagated to the caller. :meth:`close` does nothing if the
445 generator has already exited due to an exception or normal exit.
446
447Here is a simple example that demonstrates the behavior of generators and
448generator functions::
449
450 >>> def echo(value=None):
451 ... print "Execution starts when 'next()' is called for the first time."
452 ... try:
453 ... while True:
454 ... try:
455 ... value = (yield value)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000456 ... except Exception, e:
457 ... value = e
458 ... finally:
459 ... print "Don't forget to clean up when 'close()' is called."
460 ...
461 >>> generator = echo(1)
462 >>> print generator.next()
463 Execution starts when 'next()' is called for the first time.
464 1
465 >>> print generator.next()
466 None
467 >>> print generator.send(2)
468 2
469 >>> generator.throw(TypeError, "spam")
470 TypeError('spam',)
471 >>> generator.close()
472 Don't forget to clean up when 'close()' is called.
473
474
475.. seealso::
476
477 :pep:`0342` - Coroutines via Enhanced Generators
478 The proposal to enhance the API and syntax of generators, making them usable as
479 simple coroutines.
480
481
482.. _primaries:
483
484Primaries
485=========
486
487.. index:: single: primary
488
489Primaries represent the most tightly bound operations of the language. Their
490syntax is:
491
492.. productionlist::
493 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
494
495
496.. _attribute-references:
497
498Attribute references
499--------------------
500
501.. index:: pair: attribute; reference
502
503An attribute reference is a primary followed by a period and a name:
504
505.. productionlist::
506 attributeref: `primary` "." `identifier`
507
508.. index::
509 exception: AttributeError
510 object: module
511 object: list
512
513The primary must evaluate to an object of a type that supports attribute
514references, e.g., a module, list, or an instance. This object is then asked to
515produce the attribute whose name is the identifier. If this attribute is not
516available, the exception :exc:`AttributeError` is raised. Otherwise, the type
517and value of the object produced is determined by the object. Multiple
518evaluations of the same attribute reference may yield different objects.
519
520
521.. _subscriptions:
522
523Subscriptions
524-------------
525
526.. index:: single: subscription
527
528.. index::
529 object: sequence
530 object: mapping
531 object: string
532 object: tuple
533 object: list
534 object: dictionary
535 pair: sequence; item
536
537A subscription selects an item of a sequence (string, tuple or list) or mapping
538(dictionary) object:
539
540.. productionlist::
541 subscription: `primary` "[" `expression_list` "]"
542
543The primary must evaluate to an object of a sequence or mapping type.
544
545If the primary is a mapping, the expression list must evaluate to an object
546whose value is one of the keys of the mapping, and the subscription selects the
547value in the mapping that corresponds to that key. (The expression list is a
548tuple except if it has exactly one item.)
549
550If the primary is a sequence, the expression (list) must evaluate to a plain
551integer. If this value is negative, the length of the sequence is added to it
552(so that, e.g., ``x[-1]`` selects the last item of ``x``.) The resulting value
553must be a nonnegative integer less than the number of items in the sequence, and
554the subscription selects the item whose index is that value (counting from
555zero).
556
557.. index::
558 single: character
559 pair: string; item
560
561A string's items are characters. A character is not a separate data type but a
562string of exactly one character.
563
564
565.. _slicings:
566
567Slicings
568--------
569
570.. index::
571 single: slicing
572 single: slice
573
574.. index::
575 object: sequence
576 object: string
577 object: tuple
578 object: list
579
580A slicing selects a range of items in a sequence object (e.g., a string, tuple
581or list). Slicings may be used as expressions or as targets in assignment or
582:keyword:`del` statements. The syntax for a slicing:
583
584.. productionlist::
585 slicing: `simple_slicing` | `extended_slicing`
586 simple_slicing: `primary` "[" `short_slice` "]"
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000587 extended_slicing: `primary` "[" `slice_list` "]"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000588 slice_list: `slice_item` ("," `slice_item`)* [","]
589 slice_item: `expression` | `proper_slice` | `ellipsis`
590 proper_slice: `short_slice` | `long_slice`
591 short_slice: [`lower_bound`] ":" [`upper_bound`]
592 long_slice: `short_slice` ":" [`stride`]
593 lower_bound: `expression`
594 upper_bound: `expression`
595 stride: `expression`
596 ellipsis: "..."
597
598.. index:: pair: extended; slicing
599
600There is ambiguity in the formal syntax here: anything that looks like an
601expression list also looks like a slice list, so any subscription can be
602interpreted as a slicing. Rather than further complicating the syntax, this is
603disambiguated by defining that in this case the interpretation as a subscription
604takes priority over the interpretation as a slicing (this is the case if the
605slice list contains no proper slice nor ellipses). Similarly, when the slice
606list has exactly one short slice and no trailing comma, the interpretation as a
607simple slicing takes priority over that as an extended slicing.
608
609The semantics for a simple slicing are as follows. The primary must evaluate to
610a sequence object. The lower and upper bound expressions, if present, must
611evaluate to plain integers; defaults are zero and the ``sys.maxint``,
612respectively. If either bound is negative, the sequence's length is added to
613it. The slicing now selects all items with index *k* such that ``i <= k < j``
614where *i* and *j* are the specified lower and upper bounds. This may be an
615empty sequence. It is not an error if *i* or *j* lie outside the range of valid
616indexes (such items don't exist so they aren't selected).
617
618.. index::
619 single: start (slice object attribute)
620 single: stop (slice object attribute)
621 single: step (slice object attribute)
622
623The semantics for an extended slicing are as follows. The primary must evaluate
624to a mapping object, and it is indexed with a key that is constructed from the
625slice list, as follows. If the slice list contains at least one comma, the key
626is a tuple containing the conversion of the slice items; otherwise, the
627conversion of the lone slice item is the key. The conversion of a slice item
628that is an expression is that expression. The conversion of an ellipsis slice
629item is the built-in ``Ellipsis`` object. The conversion of a proper slice is a
630slice object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and
631:attr:`step` attributes are the values of the expressions given as lower bound,
632upper bound and stride, respectively, substituting ``None`` for missing
633expressions.
634
635
636.. _calls:
637
638Calls
639-----
640
641.. index:: single: call
642
643.. index:: object: callable
644
645A call calls a callable object (e.g., a function) with a possibly empty series
646of arguments:
647
648.. productionlist::
649 call: `primary` "(" [`argument_list` [","]
650 : | `expression` `genexpr_for`] ")"
651 argument_list: `positional_arguments` ["," `keyword_arguments`]
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000652 : ["," "*" `expression`] ["," `keyword_arguments`]
653 : ["," "**" `expression`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000654 : | `keyword_arguments` ["," "*" `expression`]
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000655 : ["," "**" `expression`]
656 : | "*" `expression` ["," "*" `expression`] ["," "**" `expression`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000657 : | "**" `expression`
658 positional_arguments: `expression` ("," `expression`)*
659 keyword_arguments: `keyword_item` ("," `keyword_item`)*
660 keyword_item: `identifier` "=" `expression`
661
662A trailing comma may be present after the positional and keyword arguments but
663does not affect the semantics.
664
665The primary must evaluate to a callable object (user-defined functions, built-in
666functions, methods of built-in objects, class objects, methods of class
667instances, and certain class instances themselves are callable; extensions may
668define additional callable object types). All argument expressions are
669evaluated before the call is attempted. Please refer to section :ref:`function`
670for the syntax of formal parameter lists.
671
672If keyword arguments are present, they are first converted to positional
673arguments, as follows. First, a list of unfilled slots is created for the
674formal parameters. If there are N positional arguments, they are placed in the
675first N slots. Next, for each keyword argument, the identifier is used to
676determine the corresponding slot (if the identifier is the same as the first
677formal parameter name, the first slot is used, and so on). If the slot is
678already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
679the argument is placed in the slot, filling it (even if the expression is
680``None``, it fills the slot). When all arguments have been processed, the slots
681that are still unfilled are filled with the corresponding default value from the
682function definition. (Default values are calculated, once, when the function is
683defined; thus, a mutable object such as a list or dictionary used as default
684value will be shared by all calls that don't specify an argument value for the
685corresponding slot; this should usually be avoided.) If there are any unfilled
686slots for which no default value is specified, a :exc:`TypeError` exception is
687raised. Otherwise, the list of filled slots is used as the argument list for
688the call.
689
Georg Brandl6c14e582009-10-22 11:48:10 +0000690.. impl-detail::
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000691
Georg Brandl6c14e582009-10-22 11:48:10 +0000692 An implementation may provide built-in functions whose positional parameters
693 do not have names, even if they are 'named' for the purpose of documentation,
694 and which therefore cannot be supplied by keyword. In CPython, this is the
695 case for functions implemented in C that use :cfunc:`PyArg_ParseTuple` to
696 parse their arguments.
Georg Brandlf8770fb2008-04-27 09:39:59 +0000697
Georg Brandl8ec7f652007-08-15 14:28:01 +0000698If there are more positional arguments than there are formal parameter slots, a
699:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
700``*identifier`` is present; in this case, that formal parameter receives a tuple
701containing the excess positional arguments (or an empty tuple if there were no
702excess positional arguments).
703
704If any keyword argument does not correspond to a formal parameter name, a
705:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
706``**identifier`` is present; in this case, that formal parameter receives a
707dictionary containing the excess keyword arguments (using the keywords as keys
708and the argument values as corresponding values), or a (new) empty dictionary if
709there were no excess keyword arguments.
710
711If the syntax ``*expression`` appears in the function call, ``expression`` must
712evaluate to a sequence. Elements from this sequence are treated as if they were
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000713additional positional arguments; if there are positional arguments *x1*,...,
714*xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*, this is
715equivalent to a call with M+N positional arguments *x1*, ..., *xN*, *y1*, ...,
716*yM*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000717
Benjamin Peterson80f0ed52008-08-19 19:52:46 +0000718A consequence of this is that although the ``*expression`` syntax may appear
719*after* some keyword arguments, it is processed *before* the keyword arguments
Georg Brandl8ec7f652007-08-15 14:28:01 +0000720(and the ``**expression`` argument, if any -- see below). So::
721
722 >>> def f(a, b):
723 ... print a, b
724 ...
725 >>> f(b=1, *(2,))
726 2 1
727 >>> f(a=1, *(2,))
728 Traceback (most recent call last):
729 File "<stdin>", line 1, in ?
730 TypeError: f() got multiple values for keyword argument 'a'
731 >>> f(1, *(2,))
732 1 2
733
734It is unusual for both keyword arguments and the ``*expression`` syntax to be
735used in the same call, so in practice this confusion does not arise.
736
737If the syntax ``**expression`` appears in the function call, ``expression`` must
738evaluate to a mapping, the contents of which are treated as additional keyword
739arguments. In the case of a keyword appearing in both ``expression`` and as an
740explicit keyword argument, a :exc:`TypeError` exception is raised.
741
742Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
743used as positional argument slots or as keyword argument names. Formal
744parameters using the syntax ``(sublist)`` cannot be used as keyword argument
745names; the outermost sublist corresponds to a single unnamed argument slot, and
746the argument value is assigned to the sublist using the usual tuple assignment
747rules after all other parameter processing is done.
748
749A call always returns some value, possibly ``None``, unless it raises an
750exception. How this value is computed depends on the type of the callable
751object.
752
753If it is---
754
755a user-defined function:
756 .. index::
757 pair: function; call
758 triple: user-defined; function; call
759 object: user-defined function
760 object: function
761
762 The code block for the function is executed, passing it the argument list. The
763 first thing the code block will do is bind the formal parameters to the
764 arguments; this is described in section :ref:`function`. When the code block
765 executes a :keyword:`return` statement, this specifies the return value of the
766 function call.
767
768a built-in function or method:
769 .. index::
770 pair: function; call
771 pair: built-in function; call
772 pair: method; call
773 pair: built-in method; call
774 object: built-in method
775 object: built-in function
776 object: method
777 object: function
778
779 The result is up to the interpreter; see :ref:`built-in-funcs` for the
780 descriptions of built-in functions and methods.
781
782a class object:
783 .. index::
784 object: class
785 pair: class object; call
786
787 A new instance of that class is returned.
788
789a class instance method:
790 .. index::
791 object: class instance
792 object: instance
793 pair: class instance; call
794
795 The corresponding user-defined function is called, with an argument list that is
796 one longer than the argument list of the call: the instance becomes the first
797 argument.
798
799a class instance:
800 .. index::
801 pair: instance; call
802 single: __call__() (object method)
803
804 The class must define a :meth:`__call__` method; the effect is then the same as
805 if that method was called.
806
807
808.. _power:
809
810The power operator
811==================
812
813The power operator binds more tightly than unary operators on its left; it binds
814less tightly than unary operators on its right. The syntax is:
815
816.. productionlist::
817 power: `primary` ["**" `u_expr`]
818
819Thus, in an unparenthesized sequence of power and unary operators, the operators
820are evaluated from right to left (this does not constrain the evaluation order
Georg Brandlff457b12007-08-21 06:07:08 +0000821for the operands): ``-1**2`` results in ``-1``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000822
823The power operator has the same semantics as the built-in :func:`pow` function,
824when called with two arguments: it yields its left argument raised to the power
825of its right argument. The numeric arguments are first converted to a common
826type. The result type is that of the arguments after coercion.
827
828With mixed operand types, the coercion rules for binary arithmetic operators
829apply. For int and long int operands, the result has the same type as the
830operands (after coercion) unless the second argument is negative; in that case,
831all arguments are converted to float and a float result is delivered. For
832example, ``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``. (This last
833feature was added in Python 2.2. In Python 2.1 and before, if both arguments
834were of integer types and the second argument was negative, an exception was
835raised).
836
837Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Jeffrey Yasskin9871d8f2008-01-05 08:47:13 +0000838Raising a negative number to a fractional power results in a :exc:`ValueError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000839
840
841.. _unary:
842
Georg Brandle7cb1ce2009-02-19 08:30:06 +0000843Unary arithmetic and bitwise operations
844=======================================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000845
846.. index::
847 triple: unary; arithmetic; operation
Georg Brandlf725b952008-01-05 19:44:22 +0000848 triple: unary; bitwise; operation
Georg Brandl8ec7f652007-08-15 14:28:01 +0000849
Georg Brandle7cb1ce2009-02-19 08:30:06 +0000850All unary arithmetic and bitwise operations have the same priority:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000851
852.. productionlist::
853 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
854
855.. index::
856 single: negation
857 single: minus
858
859The unary ``-`` (minus) operator yields the negation of its numeric argument.
860
861.. index:: single: plus
862
863The unary ``+`` (plus) operator yields its numeric argument unchanged.
864
865.. index:: single: inversion
866
Georg Brandlf725b952008-01-05 19:44:22 +0000867The unary ``~`` (invert) operator yields the bitwise inversion of its plain or
868long integer argument. The bitwise inversion of ``x`` is defined as
Georg Brandl8ec7f652007-08-15 14:28:01 +0000869``-(x+1)``. It only applies to integral numbers.
870
871.. index:: exception: TypeError
872
873In all three cases, if the argument does not have the proper type, a
874:exc:`TypeError` exception is raised.
875
876
877.. _binary:
878
879Binary arithmetic operations
880============================
881
882.. index:: triple: binary; arithmetic; operation
883
884The binary arithmetic operations have the conventional priority levels. Note
885that some of these operations also apply to certain non-numeric types. Apart
886from the power operator, there are only two levels, one for multiplicative
887operators and one for additive operators:
888
889.. productionlist::
890 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
891 : | `m_expr` "%" `u_expr`
892 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
893
894.. index:: single: multiplication
895
896The ``*`` (multiplication) operator yields the product of its arguments. The
897arguments must either both be numbers, or one argument must be an integer (plain
898or long) and the other must be a sequence. In the former case, the numbers are
899converted to a common type and then multiplied together. In the latter case,
900sequence repetition is performed; a negative repetition factor yields an empty
901sequence.
902
903.. index::
904 exception: ZeroDivisionError
905 single: division
906
907The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
908their arguments. The numeric arguments are first converted to a common type.
909Plain or long integer division yields an integer of the same type; the result is
910that of mathematical division with the 'floor' function applied to the result.
911Division by zero raises the :exc:`ZeroDivisionError` exception.
912
913.. index:: single: modulo
914
915The ``%`` (modulo) operator yields the remainder from the division of the first
916argument by the second. The numeric arguments are first converted to a common
917type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
918arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
919(since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
920result with the same sign as its second operand (or zero); the absolute value of
921the result is strictly smaller than the absolute value of the second operand
922[#]_.
923
924The integer division and modulo operators are connected by the following
925identity: ``x == (x/y)*y + (x%y)``. Integer division and modulo are also
926connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x/y,
927x%y)``. These identities don't hold for floating point numbers; there similar
928identities hold approximately where ``x/y`` is replaced by ``floor(x/y)`` or
929``floor(x/y) - 1`` [#]_.
930
931In addition to performing the modulo operation on numbers, the ``%`` operator is
932also overloaded by string and unicode objects to perform string formatting (also
933known as interpolation). The syntax for string formatting is described in the
934Python Library Reference, section :ref:`string-formatting`.
935
936.. deprecated:: 2.3
937 The floor division operator, the modulo operator, and the :func:`divmod`
938 function are no longer defined for complex numbers. Instead, convert to a
939 floating point number using the :func:`abs` function if appropriate.
940
941.. index:: single: addition
942
943The ``+`` (addition) operator yields the sum of its arguments. The arguments
944must either both be numbers or both sequences of the same type. In the former
945case, the numbers are converted to a common type and then added together. In
946the latter case, the sequences are concatenated.
947
948.. index:: single: subtraction
949
950The ``-`` (subtraction) operator yields the difference of its arguments. The
951numeric arguments are first converted to a common type.
952
953
954.. _shifting:
955
956Shifting operations
957===================
958
959.. index:: pair: shifting; operation
960
961The shifting operations have lower priority than the arithmetic operations:
962
963.. productionlist::
964 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
965
966These operators accept plain or long integers as arguments. The arguments are
967converted to a common type. They shift the first argument to the left or right
968by the number of bits given by the second argument.
969
970.. index:: exception: ValueError
971
Georg Brandle9135ba2008-05-11 10:55:59 +0000972A right shift by *n* bits is defined as division by ``pow(2, n)``. A left shift
973by *n* bits is defined as multiplication with ``pow(2, n)``. Negative shift
974counts raise a :exc:`ValueError` exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000975
976
977.. _bitwise:
978
Georg Brandlf725b952008-01-05 19:44:22 +0000979Binary bitwise operations
980=========================
Georg Brandl8ec7f652007-08-15 14:28:01 +0000981
Georg Brandlf725b952008-01-05 19:44:22 +0000982.. index:: triple: binary; bitwise; operation
Georg Brandl8ec7f652007-08-15 14:28:01 +0000983
984Each of the three bitwise operations has a different priority level:
985
986.. productionlist::
987 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
988 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
989 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
990
Georg Brandlf725b952008-01-05 19:44:22 +0000991.. index:: pair: bitwise; and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000992
993The ``&`` operator yields the bitwise AND of its arguments, which must be plain
994or long integers. The arguments are converted to a common type.
995
996.. index::
Georg Brandlf725b952008-01-05 19:44:22 +0000997 pair: bitwise; xor
Georg Brandl8ec7f652007-08-15 14:28:01 +0000998 pair: exclusive; or
999
1000The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
1001must be plain or long integers. The arguments are converted to a common type.
1002
1003.. index::
Georg Brandlf725b952008-01-05 19:44:22 +00001004 pair: bitwise; or
Georg Brandl8ec7f652007-08-15 14:28:01 +00001005 pair: inclusive; or
1006
1007The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
1008must be plain or long integers. The arguments are converted to a common type.
1009
1010
1011.. _comparisons:
Georg Brandlb19be572007-12-29 10:57:00 +00001012.. _is:
1013.. _isnot:
1014.. _in:
1015.. _notin:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001016
1017Comparisons
1018===========
1019
1020.. index:: single: comparison
1021
1022.. index:: pair: C; language
1023
1024Unlike C, all comparison operations in Python have the same priority, which is
1025lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1026C, expressions like ``a < b < c`` have the interpretation that is conventional
1027in mathematics:
1028
1029.. productionlist::
1030 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1031 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
1032 : | "is" ["not"] | ["not"] "in"
1033
1034Comparisons yield boolean values: ``True`` or ``False``.
1035
1036.. index:: pair: chaining; comparisons
1037
1038Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1039``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1040cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1041
Georg Brandl32008322007-08-21 06:12:19 +00001042Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1043*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1044to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1045evaluated at most once.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001046
Georg Brandl32008322007-08-21 06:12:19 +00001047Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
Georg Brandl8ec7f652007-08-15 14:28:01 +00001048*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1049pretty).
1050
1051The forms ``<>`` and ``!=`` are equivalent; for consistency with C, ``!=`` is
1052preferred; where ``!=`` is mentioned below ``<>`` is also accepted. The ``<>``
1053spelling is considered obsolescent.
1054
1055The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1056values of two objects. The objects need not have the same type. If both are
1057numbers, they are converted to a common type. Otherwise, objects of different
1058types *always* compare unequal, and are ordered consistently but arbitrarily.
Georg Brandld7d4fd72009-07-26 14:37:28 +00001059You can control comparison behavior of objects of non-built-in types by defining
Georg Brandl8ec7f652007-08-15 14:28:01 +00001060a ``__cmp__`` method or rich comparison methods like ``__gt__``, described in
1061section :ref:`specialnames`.
1062
1063(This unusual definition of comparison was used to simplify the definition of
1064operations like sorting and the :keyword:`in` and :keyword:`not in` operators.
1065In the future, the comparison rules for objects of different types are likely to
1066change.)
1067
1068Comparison of objects of the same type depends on the type:
1069
1070* Numbers are compared arithmetically.
1071
1072* Strings are compared lexicographically using the numeric equivalents (the
1073 result of the built-in function :func:`ord`) of their characters. Unicode and
Mark Summerfield216ad332007-08-16 10:09:22 +00001074 8-bit strings are fully interoperable in this behavior. [#]_
Georg Brandl8ec7f652007-08-15 14:28:01 +00001075
1076* Tuples and lists are compared lexicographically using comparison of
1077 corresponding elements. This means that to compare equal, each element must
1078 compare equal and the two sequences must be of the same type and have the same
1079 length.
1080
1081 If not equal, the sequences are ordered the same as their first differing
1082 elements. For example, ``cmp([1,2,x], [1,2,y])`` returns the same as
1083 ``cmp(x,y)``. If the corresponding element does not exist, the shorter sequence
1084 is ordered first (for example, ``[1,2] < [1,2,3]``).
1085
1086* Mappings (dictionaries) compare equal if and only if their sorted (key, value)
1087 lists compare equal. [#]_ Outcomes other than equality are resolved
1088 consistently, but are not otherwise defined. [#]_
1089
Georg Brandld7d4fd72009-07-26 14:37:28 +00001090* Most other objects of built-in types compare unequal unless they are the same
Georg Brandl8ec7f652007-08-15 14:28:01 +00001091 object; the choice whether one object is considered smaller or larger than
1092 another one is made arbitrarily but consistently within one execution of a
1093 program.
1094
Georg Brandl2eee1d42009-10-22 15:00:06 +00001095.. _membership-test-details:
1096
Georg Brandl489343e2008-03-28 12:24:51 +00001097The operators :keyword:`in` and :keyword:`not in` test for collection
1098membership. ``x in s`` evaluates to true if *x* is a member of the collection
1099*s*, and false otherwise. ``x not in s`` returns the negation of ``x in s``.
1100The collection membership test has traditionally been bound to sequences; an
1101object is a member of a collection if the collection is a sequence and contains
1102an element equal to that object. However, it make sense for many other object
1103types to support membership tests without being a sequence. In particular,
1104dictionaries (for keys) and sets support membership testing.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001105
1106For the list and tuple types, ``x in y`` is true if and only if there exists an
1107index *i* such that ``x == y[i]`` is true.
1108
1109For the Unicode and string types, ``x in y`` is true if and only if *x* is a
1110substring of *y*. An equivalent test is ``y.find(x) != -1``. Note, *x* and *y*
1111need not be the same type; consequently, ``u'ab' in 'abc'`` will return
1112``True``. Empty strings are always considered to be a substring of any other
1113string, so ``"" in "abc"`` will return ``True``.
1114
1115.. versionchanged:: 2.3
1116 Previously, *x* was required to be a string of length ``1``.
1117
1118For user-defined classes which define the :meth:`__contains__` method, ``x in
1119y`` is true if and only if ``y.__contains__(x)`` is true.
1120
Georg Brandl2eee1d42009-10-22 15:00:06 +00001121For user-defined classes which do not define :meth:`__contains__` but do define
1122:meth:`__iter__`, ``x in y`` is true if some value ``z`` with ``x == z`` is
1123produced while iterating over ``y``. If an exception is raised during the
1124iteration, it is as if :keyword:`in` raised that exception.
1125
1126Lastly, the old-style iteration protocol is tried: if a class defines
Georg Brandl8ec7f652007-08-15 14:28:01 +00001127:meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1128integer index *i* such that ``x == y[i]``, and all lower integer indices do not
1129raise :exc:`IndexError` exception. (If any other exception is raised, it is as
1130if :keyword:`in` raised that exception).
1131
1132.. index::
1133 operator: in
1134 operator: not in
1135 pair: membership; test
1136 object: sequence
1137
1138The operator :keyword:`not in` is defined to have the inverse true value of
1139:keyword:`in`.
1140
1141.. index::
1142 operator: is
1143 operator: is not
1144 pair: identity; test
1145
1146The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1147is 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 +00001148yields the inverse truth value. [#]_
Georg Brandl8ec7f652007-08-15 14:28:01 +00001149
1150
1151.. _booleans:
Georg Brandlb19be572007-12-29 10:57:00 +00001152.. _and:
1153.. _or:
1154.. _not:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001155
1156Boolean operations
1157==================
1158
1159.. index::
1160 pair: Conditional; expression
1161 pair: Boolean; operation
1162
1163Boolean operations have the lowest priority of all Python operations:
1164
1165.. productionlist::
1166 expression: `conditional_expression` | `lambda_form`
1167 old_expression: `or_test` | `old_lambda_form`
1168 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1169 or_test: `and_test` | `or_test` "or" `and_test`
1170 and_test: `not_test` | `and_test` "and" `not_test`
1171 not_test: `comparison` | "not" `not_test`
1172
1173In the context of Boolean operations, and also when expressions are used by
1174control flow statements, the following values are interpreted as false:
1175``False``, ``None``, numeric zero of all types, and empty strings and containers
1176(including strings, tuples, lists, dictionaries, sets and frozensets). All
Benjamin Petersonfe7c26d2008-09-23 13:32:46 +00001177other values are interpreted as true. (See the :meth:`~object.__nonzero__`
1178special method for a way to change this.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001179
1180.. index:: operator: not
1181
1182The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1183otherwise.
1184
1185The expression ``x if C else y`` first evaluates *C* (*not* *x*); if *C* is
1186true, *x* is evaluated and its value is returned; otherwise, *y* is evaluated
1187and its value is returned.
1188
1189.. versionadded:: 2.5
1190
1191.. index:: operator: and
1192
1193The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1194returned; otherwise, *y* is evaluated and the resulting value is returned.
1195
1196.. index:: operator: or
1197
1198The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1199returned; otherwise, *y* is evaluated and the resulting value is returned.
1200
1201(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1202they return to ``False`` and ``True``, but rather return the last evaluated
1203argument. This is sometimes useful, e.g., if ``s`` is a string that should be
1204replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1205the desired value. Because :keyword:`not` has to invent a value anyway, it does
1206not bother to return a value of the same type as its argument, so e.g., ``not
1207'foo'`` yields ``False``, not ``''``.)
1208
1209
1210.. _lambdas:
Georg Brandl5623e502009-04-10 08:16:47 +00001211.. _lambda:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001212
1213Lambdas
1214=======
1215
1216.. index::
1217 pair: lambda; expression
1218 pair: lambda; form
1219 pair: anonymous; function
1220
1221.. productionlist::
1222 lambda_form: "lambda" [`parameter_list`]: `expression`
1223 old_lambda_form: "lambda" [`parameter_list`]: `old_expression`
1224
1225Lambda forms (lambda expressions) have the same syntactic position as
1226expressions. They are a shorthand to create anonymous functions; the expression
1227``lambda arguments: expression`` yields a function object. The unnamed object
1228behaves like a function object defined with ::
1229
1230 def name(arguments):
1231 return expression
1232
1233See section :ref:`function` for the syntax of parameter lists. Note that
1234functions created with lambda forms cannot contain statements.
1235
Georg Brandl8ec7f652007-08-15 14:28:01 +00001236
1237.. _exprlists:
1238
1239Expression lists
1240================
1241
1242.. index:: pair: expression; list
1243
1244.. productionlist::
1245 expression_list: `expression` ( "," `expression` )* [","]
1246
1247.. index:: object: tuple
1248
1249An expression list containing at least one comma yields a tuple. The length of
1250the tuple is the number of expressions in the list. The expressions are
1251evaluated from left to right.
1252
1253.. index:: pair: trailing; comma
1254
1255The trailing comma is required only to create a single tuple (a.k.a. a
1256*singleton*); it is optional in all other cases. A single expression without a
1257trailing comma doesn't create a tuple, but rather yields the value of that
1258expression. (To create an empty tuple, use an empty pair of parentheses:
1259``()``.)
1260
1261
1262.. _evalorder:
1263
1264Evaluation order
1265================
1266
1267.. index:: pair: evaluation; order
1268
1269Python evaluates expressions from left to right. Notice that while evaluating an
1270assignment, the right-hand side is evaluated before the left-hand side.
1271
1272In the following lines, expressions will be evaluated in the arithmetic order of
1273their suffixes::
1274
1275 expr1, expr2, expr3, expr4
1276 (expr1, expr2, expr3, expr4)
1277 {expr1: expr2, expr3: expr4}
1278 expr1 + expr2 * (expr3 - expr4)
Georg Brandl463f39d2008-08-08 06:42:20 +00001279 expr1(expr2, expr3, *expr4, **expr5)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001280 expr3, expr4 = expr1, expr2
1281
1282
1283.. _operator-summary:
1284
1285Summary
1286=======
1287
1288.. index:: pair: operator; precedence
1289
1290The following table summarizes the operator precedences in Python, from lowest
1291precedence (least binding) to highest precedence (most binding). Operators in
1292the same box have the same precedence. Unless the syntax is explicitly given,
1293operators are binary. Operators in the same box group left to right (except for
1294comparisons, including tests, which all have the same precedence and chain from
1295left to right --- see section :ref:`comparisons` --- and exponentiation, which
1296groups from right to left).
1297
1298+-----------------------------------------------+-------------------------------------+
1299| Operator | Description |
1300+===============================================+=====================================+
1301| :keyword:`lambda` | Lambda expression |
1302+-----------------------------------------------+-------------------------------------+
1303| :keyword:`or` | Boolean OR |
1304+-----------------------------------------------+-------------------------------------+
1305| :keyword:`and` | Boolean AND |
1306+-----------------------------------------------+-------------------------------------+
1307| :keyword:`not` *x* | Boolean NOT |
1308+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001309| :keyword:`in`, :keyword:`not` :keyword:`in`, | Comparisons, including membership |
1310| :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests, |
1311| ``<=``, ``>``, ``>=``, ``<>``, ``!=``, ``==`` | |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001312+-----------------------------------------------+-------------------------------------+
1313| ``|`` | Bitwise OR |
1314+-----------------------------------------------+-------------------------------------+
1315| ``^`` | Bitwise XOR |
1316+-----------------------------------------------+-------------------------------------+
1317| ``&`` | Bitwise AND |
1318+-----------------------------------------------+-------------------------------------+
1319| ``<<``, ``>>`` | Shifts |
1320+-----------------------------------------------+-------------------------------------+
1321| ``+``, ``-`` | Addition and subtraction |
1322+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001323| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001324+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001325| ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001326+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001327| ``**`` | Exponentiation [#]_ |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001328+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001329| ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1330| ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001331+-----------------------------------------------+-------------------------------------+
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001332| ``(expressions...)``, | Binding or tuple display, |
1333| ``[expressions...]``, | list display, |
1334| ``{key:datum...}``, | dictionary display, |
1335| ```expressions...``` | string conversion |
Georg Brandl8ec7f652007-08-15 14:28:01 +00001336+-----------------------------------------------+-------------------------------------+
1337
1338.. rubric:: Footnotes
1339
Martin v. Löwis0b667312008-05-23 19:33:13 +00001340.. [#] In Python 2.3 and later releases, a list comprehension "leaks" the control
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001341 variables of each ``for`` it contains into the containing scope. However, this
Martin v. Löwis0b667312008-05-23 19:33:13 +00001342 behavior is deprecated, and relying on it will not work in Python 3.0
Georg Brandl8ec7f652007-08-15 14:28:01 +00001343
1344.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1345 true numerically due to roundoff. For example, and assuming a platform on which
1346 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1347 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
1348 1e100``, which is numerically exactly equal to ``1e100``. Function :func:`fmod`
1349 in the :mod:`math` module returns a result whose sign matches the sign of the
1350 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1351 is more appropriate depends on the application.
1352
1353.. [#] If x is very close to an exact integer multiple of y, it's possible for
1354 ``floor(x/y)`` to be one larger than ``(x-x%y)/y`` due to rounding. In such
1355 cases, Python returns the latter result, in order to preserve that
1356 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1357
Mark Summerfield216ad332007-08-16 10:09:22 +00001358.. [#] While comparisons between unicode strings make sense at the byte
1359 level, they may be counter-intuitive to users. For example, the
Mark Summerfieldd92e8712007-10-03 08:53:21 +00001360 strings ``u"\u00C7"`` and ``u"\u0043\u0327"`` compare differently,
Mark Summerfield216ad332007-08-16 10:09:22 +00001361 even though they both represent the same unicode character (LATIN
Mark Summerfieldd92e8712007-10-03 08:53:21 +00001362 CAPTITAL LETTER C WITH CEDILLA). To compare strings in a human
1363 recognizable way, compare using :func:`unicodedata.normalize`.
Mark Summerfield216ad332007-08-16 10:09:22 +00001364
Georg Brandl8ec7f652007-08-15 14:28:01 +00001365.. [#] The implementation computes this efficiently, without constructing lists or
1366 sorting.
1367
1368.. [#] Earlier versions of Python used lexicographic comparison of the sorted (key,
1369 value) lists, but this was very expensive for the common case of comparing for
1370 equality. An even earlier version of Python compared dictionaries by identity
1371 only, but this caused surprises because people expected to be able to test a
1372 dictionary for emptiness by comparing it to ``{}``.
1373
Georg Brandlc62ef8b2009-01-03 20:55:06 +00001374.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
Georg Brandl3214a012008-07-01 20:50:02 +00001375 descriptors, you may notice seemingly unusual behaviour in certain uses of
1376 the :keyword:`is` operator, like those involving comparisons between instance
1377 methods, or constants. Check their documentation for more info.
Georg Brandle7cb1ce2009-02-19 08:30:06 +00001378
1379.. [#] The power operator ``**`` binds less tightly than an arithmetic or
1380 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.