8 .. index:: single: expression
10 This chapter explains the meaning of the elements of expressions in Python.
12 .. index:: single: BNF
14 **Syntax Notes:** In this and the following chapters, extended BNF notation will
15 be used to describe syntax, not lexical analysis. When (one alternative of) a
16 syntax rule has the form
21 .. index:: single: syntax
23 and no semantics are given, the semantics of this form of ``name`` are the same
29 Arithmetic conversions
30 ======================
32 .. index:: pair: arithmetic; conversion
34 When a description of an arithmetic operator below uses the phrase "the numeric
35 arguments are converted to a common type," the arguments are coerced using the
36 coercion rules listed at :ref:`coercion-rules`. If both arguments are standard
37 numeric types, the following coercions are applied:
39 * If either argument is a complex number, the other is converted to complex;
41 * otherwise, if either argument is a floating point number, the other is
42 converted to floating point;
44 * otherwise, if either argument is a long integer, the other is converted to
47 * otherwise, both must be plain integers and no conversion is necessary.
49 Some additional rules apply for certain operators (e.g., a string left argument
50 to the '%' operator). Extensions can define their own coercions.
58 .. index:: single: atom
60 Atoms are the most basic elements of expressions. The simplest atoms are
61 identifiers or literals. Forms enclosed in reverse quotes or in parentheses,
62 brackets or braces are also categorized syntactically as atoms. The syntax for
66 atom: `identifier` | `literal` | `enclosure`
67 enclosure: `parenth_form` | `list_display`
68 : | `generator_expression` | `dict_display` | `set_display`
69 : | `string_conversion` | `yield_atom`
81 An identifier occurring as an atom is a name. See section :ref:`identifiers`
82 for lexical definition and section :ref:`naming` for documentation of naming and
85 .. index:: exception: NameError
87 When the name is bound to an object, evaluation of the atom yields that object.
88 When a name is not bound, an attempt to evaluate it raises a :exc:`NameError`
95 **Private name mangling:** When an identifier that textually occurs in a class
96 definition begins with two or more underscore characters and does not end in two
97 or more underscores, it is considered a :dfn:`private name` of that class.
98 Private names are transformed to a longer form before code is generated for
99 them. The transformation inserts the class name in front of the name, with
100 leading underscores removed, and a single underscore inserted in front of the
101 class name. For example, the identifier ``__spam`` occurring in a class named
102 ``Ham`` will be transformed to ``_Ham__spam``. This transformation is
103 independent of the syntactical context in which the identifier is used. If the
104 transformed name is extremely long (longer than 255 characters), implementation
105 defined truncation may happen. If the class name consists only of underscores,
106 no transformation is done.
115 .. index:: single: literal
117 Python supports string literals and various numeric literals:
120 literal: `stringliteral` | `integer` | `longinteger`
121 : | `floatnumber` | `imagnumber`
123 Evaluation of a literal yields an object of the given type (string, integer,
124 long integer, floating point number, complex number) with the given value. The
125 value may be approximated in the case of floating point and imaginary (complex)
126 literals. See section :ref:`literals` for details.
129 triple: immutable; data; type
130 pair: immutable; object
132 All literals correspond to immutable data types, and hence the object's identity
133 is less important than its value. Multiple evaluations of literals with the
134 same value (either the same occurrence in the program text or a different
135 occurrence) may obtain the same object or a different object with the same
144 .. index:: single: parenthesized form
146 A parenthesized form is an optional expression list enclosed in parentheses:
149 parenth_form: "(" [`expression_list`] ")"
151 A parenthesized expression list yields whatever that expression list yields: if
152 the list contains at least one comma, it yields a tuple; otherwise, it yields
153 the single expression that makes up the expression list.
155 .. index:: pair: empty; tuple
157 An empty pair of parentheses yields an empty tuple object. Since tuples are
158 immutable, the rules for literals apply (i.e., two occurrences of the empty
159 tuple may or may not yield the same object).
165 Note that tuples are not formed by the parentheses, but rather by use of the
166 comma operator. The exception is the empty tuple, for which parentheses *are*
167 required --- allowing unparenthesized "nothing" in expressions would cause
168 ambiguities and allow common typos to pass uncaught.
178 pair: list; comprehensions
180 A list display is a possibly empty series of expressions enclosed in square
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`]
192 pair: list; comprehensions
196 A list display yields a new list object. Its contents are specified by
197 providing either a list of expressions or a list comprehension. When a
198 comma-separated list of expressions is supplied, its elements are evaluated from
199 left to right and placed into the list object in that order. When a list
200 comprehension is supplied, it consists of a single expression followed by at
201 least one :keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if`
202 clauses. In this case, the elements of the new list are those that would be
203 produced by considering each of the :keyword:`for` or :keyword:`if` clauses a
204 block, nesting from left to right, and evaluating the expression to produce a
205 list element each time the innermost block is reached [#]_.
210 Displays for sets and dictionaries
211 ----------------------------------
213 For constructing a set or a dictionary Python provides special syntax
214 called "displays", each of them in two flavors:
216 * either the container contents are listed explicitly, or
218 * they are computed via a set of looping and filtering instructions, called a
219 :dfn:`comprehension`.
221 Common syntax elements for comprehensions are:
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`]
229 The 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.
231 In this case, the elements of the new container are those that would be produced
232 by considering each of the :keyword:`for` or :keyword:`if` clauses a block,
233 nesting from left to right, and evaluating the expression to produce an element
234 each time the innermost block is reached.
236 Note that the comprehension is executed in a separate scope, so names assigned
237 to in the target list don't "leak" in the enclosing scope.
242 Generator expressions
243 ---------------------
245 .. index:: pair: generator; expression
248 A generator expression is a compact generator notation in parentheses:
251 generator_expression: "(" `expression` `comp_for` ")"
253 A generator expression yields a new generator object. Its syntax is the same as
254 for comprehensions, except that it is enclosed in parentheses instead of
255 brackets or curly braces.
257 Variables used in the generator expression are evaluated lazily when the
258 :meth:`__next__` method is called for generator object (in the same fashion as
259 normal generators). However, the leftmost :keyword:`for` clause is immediately
260 evaluated, so that an error produced by it can be seen before any other possible
261 error in the code that handles the generator expression. Subsequent
262 :keyword:`for` clauses cannot be evaluated immediately since they may depend on
263 the previous :keyword:`for` loop. For example: ``(x*y for x in range(10) for y
266 The parentheses can be omitted on calls with only one argument. See section
267 :ref:`calls` for the detail.
274 .. index:: pair: dictionary; display
275 key, datum, key/datum pair
278 A dictionary display is a possibly empty series of key/datum pairs enclosed in
282 dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
283 key_datum_list: `key_datum` ("," `key_datum`)* [","]
284 key_datum: `expression` ":" `expression`
285 dict_comprehension: `expression` ":" `expression` `comp_for`
287 A dictionary display yields a new dictionary object.
289 If a comma-separated sequence of key/datum pairs is given, they are evaluated
290 from left to right to define the entries of the dictionary: each key object is
291 used as a key into the dictionary to store the corresponding datum. This means
292 that you can specify the same key multiple times in the key/datum list, and the
293 final dictionary's value for that key will be the last one given.
295 A dict comprehension, in contrast to list and set comprehensions, needs two
296 expressions separated with a colon followed by the usual "for" and "if" clauses.
297 When the comprehension is run, the resulting key and value elements are inserted
298 in the new dictionary in the order they are produced.
300 .. index:: pair: immutable; object
303 Restrictions on the types of the key values are listed earlier in section
304 :ref:`types`. (To summarize, the key type should be :term:`hashable`, which excludes
305 all mutable objects.) Clashes between duplicate keys are not detected; the last
306 datum (textually rightmost in the display) stored for a given key value
315 .. index:: pair: set; display
318 A set display is denoted by curly braces and distinguishable from dictionary
319 displays by the lack of colons separating keys and values:
322 set_display: "{" (`expression_list` | `comprehension`) "}"
324 A set display yields a new mutable set object, the contents being specified by
325 either a sequence of expressions or a comprehension. When a comma-separated
326 list of expressions is supplied, its elements are evaluated from left to right
327 and added to the set object. When a comprehension is supplied, the set is
328 constructed from the elements resulting from the comprehension.
330 An empty set cannot be constructed with ``{}``; this literal constructs an empty
334 .. _string-conversions:
340 pair: string; conversion
341 pair: reverse; quotes
342 pair: backward; quotes
345 A string conversion is an expression list enclosed in reverse (a.k.a. backward)
349 string_conversion: "'" `expression_list` "'"
351 A string conversion evaluates the contained expression list and converts the
352 resulting object into a string according to rules specific to its type.
354 If the object is a string, a number, ``None``, or a tuple, list or dictionary
355 containing only objects whose type is one of these, the resulting string is a
356 valid 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
358 floating point numbers are involved).
360 (In particular, converting a string adds quotes around it and converts "funny"
361 characters to escape sequences that are safe to print.)
363 .. index:: object: recursive
365 Recursive objects (for example, lists or dictionaries that contain a reference
366 to themselves, directly or indirectly) use ``...`` to indicate a recursive
367 reference, and the result cannot be passed to :func:`eval` to get an equal value
368 (:exc:`SyntaxError` will be raised instead).
374 The built-in function :func:`repr` performs exactly the same conversion in its
375 argument as enclosing it in parentheses and reverse quotes does. The built-in
376 function :func:`str` performs a similar but more user-friendly conversion.
386 pair: yield; expression
387 pair: generator; function
390 yield_atom: "(" `yield_expression` ")"
391 yield_expression: "yield" [`expression_list`]
393 .. versionadded:: 2.5
395 The :keyword:`yield` expression is only used when defining a generator function,
396 and 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
398 definition to create a generator function instead of a normal function.
400 When a generator function is called, it returns an iterator known as a
401 generator. That generator then controls the execution of a generator function.
402 The execution starts when one of the generator's methods is called. At that
403 time, the execution proceeds to the first :keyword:`yield` expression, where it
404 is suspended again, returning the value of :token:`expression_list` to
405 generator's caller. By suspended we mean that all local state is retained,
406 including the current bindings of local variables, the instruction pointer, and
407 the internal evaluation stack. When the execution is resumed by calling one of
408 the 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
413 .. index:: single: coroutine
415 All of this makes generator functions quite similar to coroutines; they yield
416 multiple times, they have more than one entry point and their execution can be
417 suspended. The only difference is that a generator function cannot control
418 where should the execution continue after it yields; the control is always
419 transfered to the generator's caller.
421 .. index:: object: generator
423 The following generator's methods can be used to control the execution of a
426 .. index:: exception: StopIteration
429 .. method:: generator.next()
431 Starts the execution of a generator function or resumes it at the last executed
432 :keyword:`yield` expression. When a generator function is resumed with a
433 :meth:`next` method, the current :keyword:`yield` expression always evaluates to
434 :const:`None`. The execution then continues to the next :keyword:`yield`
435 expression, where the generator is suspended again, and the value of the
436 :token:`expression_list` is returned to :meth:`next`'s caller. If the generator
437 exits without yielding another value, a :exc:`StopIteration` exception is
441 .. method:: generator.send(value)
443 Resumes the execution and "sends" a value into the generator function. The
444 ``value`` argument becomes the result of the current :keyword:`yield`
445 expression. The :meth:`send` method returns the next value yielded by the
446 generator, or raises :exc:`StopIteration` if the generator exits without
447 yielding another value. When :meth:`send` is called to start the generator, it
448 must be called with :const:`None` as the argument, because there is no
449 :keyword:`yield` expression that could receive the value.
452 .. method:: generator.throw(type[, value[, traceback]])
454 Raises an exception of type ``type`` at the point where generator was paused,
455 and returns the next value yielded by the generator function. If the generator
456 exits without yielding another value, a :exc:`StopIteration` exception is
457 raised. If the generator function does not catch the passed-in exception, or
458 raises a different exception, then that exception propagates to the caller.
460 .. index:: exception: GeneratorExit
463 .. method:: generator.close()
465 Raises a :exc:`GeneratorExit` at the point where the generator function was
466 paused. If the generator function then raises :exc:`StopIteration` (by exiting
467 normally, or due to already being closed) or :exc:`GeneratorExit` (by not
468 catching the exception), close returns to its caller. If the generator yields a
469 value, a :exc:`RuntimeError` is raised. If the generator raises any other
470 exception, it is propagated to the caller. :meth:`close` does nothing if the
471 generator has already exited due to an exception or normal exit.
473 Here is a simple example that demonstrates the behavior of generators and
474 generator functions::
476 >>> def echo(value=None):
477 ... print "Execution starts when 'next()' is called for the first time."
481 ... value = (yield value)
482 ... except Exception, e:
485 ... print "Don't forget to clean up when 'close()' is called."
487 >>> generator = echo(1)
488 >>> print generator.next()
489 Execution starts when 'next()' is called for the first time.
491 >>> print generator.next()
493 >>> print generator.send(2)
495 >>> generator.throw(TypeError, "spam")
497 >>> generator.close()
498 Don't forget to clean up when 'close()' is called.
503 :pep:`0342` - Coroutines via Enhanced Generators
504 The proposal to enhance the API and syntax of generators, making them usable as
513 .. index:: single: primary
515 Primaries represent the most tightly bound operations of the language. Their
519 primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`
522 .. _attribute-references:
527 .. index:: pair: attribute; reference
529 An attribute reference is a primary followed by a period and a name:
532 attributeref: `primary` "." `identifier`
535 exception: AttributeError
539 The primary must evaluate to an object of a type that supports attribute
540 references, e.g., a module, list, or an instance. This object is then asked to
541 produce the attribute whose name is the identifier. If this attribute is not
542 available, the exception :exc:`AttributeError` is raised. Otherwise, the type
543 and value of the object produced is determined by the object. Multiple
544 evaluations of the same attribute reference may yield different objects.
552 .. index:: single: subscription
563 A subscription selects an item of a sequence (string, tuple or list) or mapping
567 subscription: `primary` "[" `expression_list` "]"
569 The primary must evaluate to an object of a sequence or mapping type.
571 If the primary is a mapping, the expression list must evaluate to an object
572 whose value is one of the keys of the mapping, and the subscription selects the
573 value in the mapping that corresponds to that key. (The expression list is a
574 tuple except if it has exactly one item.)
576 If the primary is a sequence, the expression (list) must evaluate to a plain
577 integer. If this value is negative, the length of the sequence is added to it
578 (so that, e.g., ``x[-1]`` selects the last item of ``x``.) The resulting value
579 must be a nonnegative integer less than the number of items in the sequence, and
580 the subscription selects the item whose index is that value (counting from
587 A string's items are characters. A character is not a separate data type but a
588 string of exactly one character.
606 A slicing selects a range of items in a sequence object (e.g., a string, tuple
607 or list). Slicings may be used as expressions or as targets in assignment or
608 :keyword:`del` statements. The syntax for a slicing:
611 slicing: `simple_slicing` | `extended_slicing`
612 simple_slicing: `primary` "[" `short_slice` "]"
613 extended_slicing: `primary` "[" `slice_list` "]"
614 slice_list: `slice_item` ("," `slice_item`)* [","]
615 slice_item: `expression` | `proper_slice` | `ellipsis`
616 proper_slice: `short_slice` | `long_slice`
617 short_slice: [`lower_bound`] ":" [`upper_bound`]
618 long_slice: `short_slice` ":" [`stride`]
619 lower_bound: `expression`
620 upper_bound: `expression`
624 .. index:: pair: extended; slicing
626 There is ambiguity in the formal syntax here: anything that looks like an
627 expression list also looks like a slice list, so any subscription can be
628 interpreted as a slicing. Rather than further complicating the syntax, this is
629 disambiguated by defining that in this case the interpretation as a subscription
630 takes priority over the interpretation as a slicing (this is the case if the
631 slice list contains no proper slice nor ellipses). Similarly, when the slice
632 list has exactly one short slice and no trailing comma, the interpretation as a
633 simple slicing takes priority over that as an extended slicing.
635 The semantics for a simple slicing are as follows. The primary must evaluate to
636 a sequence object. The lower and upper bound expressions, if present, must
637 evaluate to plain integers; defaults are zero and the ``sys.maxint``,
638 respectively. If either bound is negative, the sequence's length is added to
639 it. The slicing now selects all items with index *k* such that ``i <= k < j``
640 where *i* and *j* are the specified lower and upper bounds. This may be an
641 empty sequence. It is not an error if *i* or *j* lie outside the range of valid
642 indexes (such items don't exist so they aren't selected).
645 single: start (slice object attribute)
646 single: stop (slice object attribute)
647 single: step (slice object attribute)
649 The semantics for an extended slicing are as follows. The primary must evaluate
650 to a mapping object, and it is indexed with a key that is constructed from the
651 slice list, as follows. If the slice list contains at least one comma, the key
652 is a tuple containing the conversion of the slice items; otherwise, the
653 conversion of the lone slice item is the key. The conversion of a slice item
654 that is an expression is that expression. The conversion of an ellipsis slice
655 item is the built-in ``Ellipsis`` object. The conversion of a proper slice is a
656 slice object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and
657 :attr:`step` attributes are the values of the expressions given as lower bound,
658 upper bound and stride, respectively, substituting ``None`` for missing
667 .. index:: single: call
669 .. index:: object: callable
671 A call calls a callable object (e.g., a function) with a possibly empty series
675 call: `primary` "(" [`argument_list` [","]
676 : | `expression` `genexpr_for`] ")"
677 argument_list: `positional_arguments` ["," `keyword_arguments`]
678 : ["," "*" `expression`] ["," `keyword_arguments`]
679 : ["," "**" `expression`]
680 : | `keyword_arguments` ["," "*" `expression`]
681 : ["," "**" `expression`]
682 : | "*" `expression` ["," "*" `expression`] ["," "**" `expression`]
683 : | "**" `expression`
684 positional_arguments: `expression` ("," `expression`)*
685 keyword_arguments: `keyword_item` ("," `keyword_item`)*
686 keyword_item: `identifier` "=" `expression`
688 A trailing comma may be present after the positional and keyword arguments but
689 does not affect the semantics.
691 The primary must evaluate to a callable object (user-defined functions, built-in
692 functions, methods of built-in objects, class objects, methods of class
693 instances, and certain class instances themselves are callable; extensions may
694 define additional callable object types). All argument expressions are
695 evaluated before the call is attempted. Please refer to section :ref:`function`
696 for the syntax of formal parameter lists.
698 If keyword arguments are present, they are first converted to positional
699 arguments, as follows. First, a list of unfilled slots is created for the
700 formal parameters. If there are N positional arguments, they are placed in the
701 first N slots. Next, for each keyword argument, the identifier is used to
702 determine the corresponding slot (if the identifier is the same as the first
703 formal parameter name, the first slot is used, and so on). If the slot is
704 already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
705 the argument is placed in the slot, filling it (even if the expression is
706 ``None``, it fills the slot). When all arguments have been processed, the slots
707 that are still unfilled are filled with the corresponding default value from the
708 function definition. (Default values are calculated, once, when the function is
709 defined; thus, a mutable object such as a list or dictionary used as default
710 value will be shared by all calls that don't specify an argument value for the
711 corresponding slot; this should usually be avoided.) If there are any unfilled
712 slots for which no default value is specified, a :exc:`TypeError` exception is
713 raised. Otherwise, the list of filled slots is used as the argument list for
718 An implementation may provide built-in functions whose positional parameters
719 do not have names, even if they are 'named' for the purpose of documentation,
720 and which therefore cannot be supplied by keyword. In CPython, this is the
721 case for functions implemented in C that use :cfunc:`PyArg_ParseTuple` to
722 parse their arguments.
724 If there are more positional arguments than there are formal parameter slots, a
725 :exc:`TypeError` exception is raised, unless a formal parameter using the syntax
726 ``*identifier`` is present; in this case, that formal parameter receives a tuple
727 containing the excess positional arguments (or an empty tuple if there were no
728 excess positional arguments).
730 If any keyword argument does not correspond to a formal parameter name, a
731 :exc:`TypeError` exception is raised, unless a formal parameter using the syntax
732 ``**identifier`` is present; in this case, that formal parameter receives a
733 dictionary containing the excess keyword arguments (using the keywords as keys
734 and the argument values as corresponding values), or a (new) empty dictionary if
735 there were no excess keyword arguments.
737 If the syntax ``*expression`` appears in the function call, ``expression`` must
738 evaluate to a sequence. Elements from this sequence are treated as if they were
739 additional positional arguments; if there are positional arguments *x1*,...,
740 *xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*, this is
741 equivalent to a call with M+N positional arguments *x1*, ..., *xN*, *y1*, ...,
744 A consequence of this is that although the ``*expression`` syntax may appear
745 *after* some keyword arguments, it is processed *before* the keyword arguments
746 (and the ``**expression`` argument, if any -- see below). So::
754 Traceback (most recent call last):
755 File "<stdin>", line 1, in ?
756 TypeError: f() got multiple values for keyword argument 'a'
760 It is unusual for both keyword arguments and the ``*expression`` syntax to be
761 used in the same call, so in practice this confusion does not arise.
763 If the syntax ``**expression`` appears in the function call, ``expression`` must
764 evaluate to a mapping, the contents of which are treated as additional keyword
765 arguments. In the case of a keyword appearing in both ``expression`` and as an
766 explicit keyword argument, a :exc:`TypeError` exception is raised.
768 Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
769 used as positional argument slots or as keyword argument names. Formal
770 parameters using the syntax ``(sublist)`` cannot be used as keyword argument
771 names; the outermost sublist corresponds to a single unnamed argument slot, and
772 the argument value is assigned to the sublist using the usual tuple assignment
773 rules after all other parameter processing is done.
775 A call always returns some value, possibly ``None``, unless it raises an
776 exception. How this value is computed depends on the type of the callable
781 a user-defined function:
784 triple: user-defined; function; call
785 object: user-defined function
788 The code block for the function is executed, passing it the argument list. The
789 first thing the code block will do is bind the formal parameters to the
790 arguments; this is described in section :ref:`function`. When the code block
791 executes a :keyword:`return` statement, this specifies the return value of the
794 a built-in function or method:
797 pair: built-in function; call
799 pair: built-in method; call
800 object: built-in method
801 object: built-in function
805 The result is up to the interpreter; see :ref:`built-in-funcs` for the
806 descriptions of built-in functions and methods.
811 pair: class object; call
813 A new instance of that class is returned.
815 a class instance method:
817 object: class instance
819 pair: class instance; call
821 The corresponding user-defined function is called, with an argument list that is
822 one longer than the argument list of the call: the instance becomes the first
828 single: __call__() (object method)
830 The class must define a :meth:`__call__` method; the effect is then the same as
831 if that method was called.
839 The power operator binds more tightly than unary operators on its left; it binds
840 less tightly than unary operators on its right. The syntax is:
843 power: `primary` ["**" `u_expr`]
845 Thus, in an unparenthesized sequence of power and unary operators, the operators
846 are evaluated from right to left (this does not constrain the evaluation order
847 for the operands): ``-1**2`` results in ``-1``.
849 The power operator has the same semantics as the built-in :func:`pow` function,
850 when called with two arguments: it yields its left argument raised to the power
851 of its right argument. The numeric arguments are first converted to a common
852 type. The result type is that of the arguments after coercion.
854 With mixed operand types, the coercion rules for binary arithmetic operators
855 apply. For int and long int operands, the result has the same type as the
856 operands (after coercion) unless the second argument is negative; in that case,
857 all arguments are converted to float and a float result is delivered. For
858 example, ``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``. (This last
859 feature was added in Python 2.2. In Python 2.1 and before, if both arguments
860 were of integer types and the second argument was negative, an exception was
863 Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
864 Raising a negative number to a fractional power results in a :exc:`ValueError`.
869 Unary arithmetic and bitwise operations
870 =======================================
873 triple: unary; arithmetic; operation
874 triple: unary; bitwise; operation
876 All unary arithmetic and bitwise operations have the same priority:
879 u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`
885 The unary ``-`` (minus) operator yields the negation of its numeric argument.
887 .. index:: single: plus
889 The unary ``+`` (plus) operator yields its numeric argument unchanged.
891 .. index:: single: inversion
893 The unary ``~`` (invert) operator yields the bitwise inversion of its plain or
894 long integer argument. The bitwise inversion of ``x`` is defined as
895 ``-(x+1)``. It only applies to integral numbers.
897 .. index:: exception: TypeError
899 In all three cases, if the argument does not have the proper type, a
900 :exc:`TypeError` exception is raised.
905 Binary arithmetic operations
906 ============================
908 .. index:: triple: binary; arithmetic; operation
910 The binary arithmetic operations have the conventional priority levels. Note
911 that some of these operations also apply to certain non-numeric types. Apart
912 from the power operator, there are only two levels, one for multiplicative
913 operators and one for additive operators:
916 m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
917 : | `m_expr` "%" `u_expr`
918 a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`
920 .. index:: single: multiplication
922 The ``*`` (multiplication) operator yields the product of its arguments. The
923 arguments must either both be numbers, or one argument must be an integer (plain
924 or long) and the other must be a sequence. In the former case, the numbers are
925 converted to a common type and then multiplied together. In the latter case,
926 sequence repetition is performed; a negative repetition factor yields an empty
930 exception: ZeroDivisionError
933 The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
934 their arguments. The numeric arguments are first converted to a common type.
935 Plain or long integer division yields an integer of the same type; the result is
936 that of mathematical division with the 'floor' function applied to the result.
937 Division by zero raises the :exc:`ZeroDivisionError` exception.
939 .. index:: single: modulo
941 The ``%`` (modulo) operator yields the remainder from the division of the first
942 argument by the second. The numeric arguments are first converted to a common
943 type. A zero right argument raises the :exc:`ZeroDivisionError` exception. The
944 arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
945 (since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a
946 result with the same sign as its second operand (or zero); the absolute value of
947 the result is strictly smaller than the absolute value of the second operand
950 The integer division and modulo operators are connected by the following
951 identity: ``x == (x/y)*y + (x%y)``. Integer division and modulo are also
952 connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x/y,
953 x%y)``. These identities don't hold for floating point numbers; there similar
954 identities hold approximately where ``x/y`` is replaced by ``floor(x/y)`` or
955 ``floor(x/y) - 1`` [#]_.
957 In addition to performing the modulo operation on numbers, the ``%`` operator is
958 also overloaded by string and unicode objects to perform string formatting (also
959 known as interpolation). The syntax for string formatting is described in the
960 Python Library Reference, section :ref:`string-formatting`.
963 The floor division operator, the modulo operator, and the :func:`divmod`
964 function are no longer defined for complex numbers. Instead, convert to a
965 floating point number using the :func:`abs` function if appropriate.
967 .. index:: single: addition
969 The ``+`` (addition) operator yields the sum of its arguments. The arguments
970 must either both be numbers or both sequences of the same type. In the former
971 case, the numbers are converted to a common type and then added together. In
972 the latter case, the sequences are concatenated.
974 .. index:: single: subtraction
976 The ``-`` (subtraction) operator yields the difference of its arguments. The
977 numeric arguments are first converted to a common type.
985 .. index:: pair: shifting; operation
987 The shifting operations have lower priority than the arithmetic operations:
990 shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`
992 These operators accept plain or long integers as arguments. The arguments are
993 converted to a common type. They shift the first argument to the left or right
994 by the number of bits given by the second argument.
996 .. index:: exception: ValueError
998 A right shift by *n* bits is defined as division by ``pow(2, n)``. A left shift
999 by *n* bits is defined as multiplication with ``pow(2, n)``. Negative shift
1000 counts raise a :exc:`ValueError` exception.
1005 Binary bitwise operations
1006 =========================
1008 .. index:: triple: binary; bitwise; operation
1010 Each of the three bitwise operations has a different priority level:
1013 and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
1014 xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
1015 or_expr: `xor_expr` | `or_expr` "|" `xor_expr`
1017 .. index:: pair: bitwise; and
1019 The ``&`` operator yields the bitwise AND of its arguments, which must be plain
1020 or long integers. The arguments are converted to a common type.
1026 The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
1027 must be plain or long integers. The arguments are converted to a common type.
1033 The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
1034 must be plain or long integers. The arguments are converted to a common type.
1046 .. index:: single: comparison
1048 .. index:: pair: C; language
1050 Unlike C, all comparison operations in Python have the same priority, which is
1051 lower than that of any arithmetic, shifting or bitwise operation. Also unlike
1052 C, expressions like ``a < b < c`` have the interpretation that is conventional
1056 comparison: `or_expr` ( `comp_operator` `or_expr` )*
1057 comp_operator: "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
1058 : | "is" ["not"] | ["not"] "in"
1060 Comparisons yield boolean values: ``True`` or ``False``.
1062 .. index:: pair: chaining; comparisons
1064 Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
1065 ``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
1066 cases ``z`` is not evaluated at all when ``x < y`` is found to be false).
1068 Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
1069 *opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
1070 to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
1071 evaluated at most once.
1073 Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
1074 *c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
1077 The forms ``<>`` and ``!=`` are equivalent; for consistency with C, ``!=`` is
1078 preferred; where ``!=`` is mentioned below ``<>`` is also accepted. The ``<>``
1079 spelling is considered obsolescent.
1081 The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
1082 values of two objects. The objects need not have the same type. If both are
1083 numbers, they are converted to a common type. Otherwise, objects of different
1084 types *always* compare unequal, and are ordered consistently but arbitrarily.
1085 You can control comparison behavior of objects of non-built-in types by defining
1086 a ``__cmp__`` method or rich comparison methods like ``__gt__``, described in
1087 section :ref:`specialnames`.
1089 (This unusual definition of comparison was used to simplify the definition of
1090 operations like sorting and the :keyword:`in` and :keyword:`not in` operators.
1091 In the future, the comparison rules for objects of different types are likely to
1094 Comparison of objects of the same type depends on the type:
1096 * Numbers are compared arithmetically.
1098 * Strings are compared lexicographically using the numeric equivalents (the
1099 result of the built-in function :func:`ord`) of their characters. Unicode and
1100 8-bit strings are fully interoperable in this behavior. [#]_
1102 * Tuples and lists are compared lexicographically using comparison of
1103 corresponding elements. This means that to compare equal, each element must
1104 compare equal and the two sequences must be of the same type and have the same
1107 If not equal, the sequences are ordered the same as their first differing
1108 elements. For example, ``cmp([1,2,x], [1,2,y])`` returns the same as
1109 ``cmp(x,y)``. If the corresponding element does not exist, the shorter sequence
1110 is ordered first (for example, ``[1,2] < [1,2,3]``).
1112 * Mappings (dictionaries) compare equal if and only if their sorted (key, value)
1113 lists compare equal. [#]_ Outcomes other than equality are resolved
1114 consistently, but are not otherwise defined. [#]_
1116 * Most other objects of built-in types compare unequal unless they are the same
1117 object; the choice whether one object is considered smaller or larger than
1118 another one is made arbitrarily but consistently within one execution of a
1121 .. _membership-test-details:
1123 The operators :keyword:`in` and :keyword:`not in` test for collection
1124 membership. ``x in s`` evaluates to true if *x* is a member of the collection
1125 *s*, and false otherwise. ``x not in s`` returns the negation of ``x in s``.
1126 The collection membership test has traditionally been bound to sequences; an
1127 object is a member of a collection if the collection is a sequence and contains
1128 an element equal to that object. However, it make sense for many other object
1129 types to support membership tests without being a sequence. In particular,
1130 dictionaries (for keys) and sets support membership testing.
1132 For the list and tuple types, ``x in y`` is true if and only if there exists an
1133 index *i* such that ``x == y[i]`` is true.
1135 For the Unicode and string types, ``x in y`` is true if and only if *x* is a
1136 substring of *y*. An equivalent test is ``y.find(x) != -1``. Note, *x* and *y*
1137 need not be the same type; consequently, ``u'ab' in 'abc'`` will return
1138 ``True``. Empty strings are always considered to be a substring of any other
1139 string, so ``"" in "abc"`` will return ``True``.
1141 .. versionchanged:: 2.3
1142 Previously, *x* was required to be a string of length ``1``.
1144 For user-defined classes which define the :meth:`__contains__` method, ``x in
1145 y`` is true if and only if ``y.__contains__(x)`` is true.
1147 For user-defined classes which do not define :meth:`__contains__` but do define
1148 :meth:`__iter__`, ``x in y`` is true if some value ``z`` with ``x == z`` is
1149 produced while iterating over ``y``. If an exception is raised during the
1150 iteration, it is as if :keyword:`in` raised that exception.
1152 Lastly, the old-style iteration protocol is tried: if a class defines
1153 :meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative
1154 integer index *i* such that ``x == y[i]``, and all lower integer indices do not
1155 raise :exc:`IndexError` exception. (If any other exception is raised, it is as
1156 if :keyword:`in` raised that exception).
1161 pair: membership; test
1164 The operator :keyword:`not in` is defined to have the inverse true value of
1170 pair: identity; test
1172 The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
1173 is y`` is true if and only if *x* and *y* are the same object. ``x is not y``
1174 yields the inverse truth value. [#]_
1186 pair: Conditional; expression
1187 pair: Boolean; operation
1189 Boolean operations have the lowest priority of all Python operations:
1192 expression: `conditional_expression` | `lambda_form`
1193 old_expression: `or_test` | `old_lambda_form`
1194 conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
1195 or_test: `and_test` | `or_test` "or" `and_test`
1196 and_test: `not_test` | `and_test` "and" `not_test`
1197 not_test: `comparison` | "not" `not_test`
1199 In the context of Boolean operations, and also when expressions are used by
1200 control flow statements, the following values are interpreted as false:
1201 ``False``, ``None``, numeric zero of all types, and empty strings and containers
1202 (including strings, tuples, lists, dictionaries, sets and frozensets). All
1203 other values are interpreted as true. (See the :meth:`~object.__nonzero__`
1204 special method for a way to change this.)
1206 .. index:: operator: not
1208 The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
1211 The expression ``x if C else y`` first evaluates *C* (*not* *x*); if *C* is
1212 true, *x* is evaluated and its value is returned; otherwise, *y* is evaluated
1213 and its value is returned.
1215 .. versionadded:: 2.5
1217 .. index:: operator: and
1219 The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
1220 returned; otherwise, *y* is evaluated and the resulting value is returned.
1222 .. index:: operator: or
1224 The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
1225 returned; otherwise, *y* is evaluated and the resulting value is returned.
1227 (Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
1228 they return to ``False`` and ``True``, but rather return the last evaluated
1229 argument. This is sometimes useful, e.g., if ``s`` is a string that should be
1230 replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
1231 the desired value. Because :keyword:`not` has to invent a value anyway, it does
1232 not bother to return a value of the same type as its argument, so e.g., ``not
1233 'foo'`` yields ``False``, not ``''``.)
1243 pair: lambda; expression
1245 pair: anonymous; function
1248 lambda_form: "lambda" [`parameter_list`]: `expression`
1249 old_lambda_form: "lambda" [`parameter_list`]: `old_expression`
1251 Lambda forms (lambda expressions) have the same syntactic position as
1252 expressions. They are a shorthand to create anonymous functions; the expression
1253 ``lambda arguments: expression`` yields a function object. The unnamed object
1254 behaves like a function object defined with ::
1256 def name(arguments):
1259 See section :ref:`function` for the syntax of parameter lists. Note that
1260 functions created with lambda forms cannot contain statements.
1268 .. index:: pair: expression; list
1271 expression_list: `expression` ( "," `expression` )* [","]
1273 .. index:: object: tuple
1275 An expression list containing at least one comma yields a tuple. The length of
1276 the tuple is the number of expressions in the list. The expressions are
1277 evaluated from left to right.
1279 .. index:: pair: trailing; comma
1281 The trailing comma is required only to create a single tuple (a.k.a. a
1282 *singleton*); it is optional in all other cases. A single expression without a
1283 trailing comma doesn't create a tuple, but rather yields the value of that
1284 expression. (To create an empty tuple, use an empty pair of parentheses:
1293 .. index:: pair: evaluation; order
1295 Python evaluates expressions from left to right. Notice that while evaluating an
1296 assignment, the right-hand side is evaluated before the left-hand side.
1298 In the following lines, expressions will be evaluated in the arithmetic order of
1301 expr1, expr2, expr3, expr4
1302 (expr1, expr2, expr3, expr4)
1303 {expr1: expr2, expr3: expr4}
1304 expr1 + expr2 * (expr3 - expr4)
1305 expr1(expr2, expr3, *expr4, **expr5)
1306 expr3, expr4 = expr1, expr2
1309 .. _operator-summary:
1314 .. index:: pair: operator; precedence
1316 The following table summarizes the operator precedences in Python, from lowest
1317 precedence (least binding) to highest precedence (most binding). Operators in
1318 the same box have the same precedence. Unless the syntax is explicitly given,
1319 operators are binary. Operators in the same box group left to right (except for
1320 comparisons, including tests, which all have the same precedence and chain from
1321 left to right --- see section :ref:`comparisons` --- and exponentiation, which
1322 groups from right to left).
1324 +-----------------------------------------------+-------------------------------------+
1325 | Operator | Description |
1326 +===============================================+=====================================+
1327 | :keyword:`lambda` | Lambda expression |
1328 +-----------------------------------------------+-------------------------------------+
1329 | :keyword:`or` | Boolean OR |
1330 +-----------------------------------------------+-------------------------------------+
1331 | :keyword:`and` | Boolean AND |
1332 +-----------------------------------------------+-------------------------------------+
1333 | :keyword:`not` *x* | Boolean NOT |
1334 +-----------------------------------------------+-------------------------------------+
1335 | :keyword:`in`, :keyword:`not` :keyword:`in`, | Comparisons, including membership |
1336 | :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests, |
1337 | ``<=``, ``>``, ``>=``, ``<>``, ``!=``, ``==`` | |
1338 +-----------------------------------------------+-------------------------------------+
1339 | ``|`` | Bitwise OR |
1340 +-----------------------------------------------+-------------------------------------+
1341 | ``^`` | Bitwise XOR |
1342 +-----------------------------------------------+-------------------------------------+
1343 | ``&`` | Bitwise AND |
1344 +-----------------------------------------------+-------------------------------------+
1345 | ``<<``, ``>>`` | Shifts |
1346 +-----------------------------------------------+-------------------------------------+
1347 | ``+``, ``-`` | Addition and subtraction |
1348 +-----------------------------------------------+-------------------------------------+
1349 | ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder |
1350 +-----------------------------------------------+-------------------------------------+
1351 | ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT |
1352 +-----------------------------------------------+-------------------------------------+
1353 | ``**`` | Exponentiation [#]_ |
1354 +-----------------------------------------------+-------------------------------------+
1355 | ``x[index]``, ``x[index:index]``, | Subscription, slicing, |
1356 | ``x(arguments...)``, ``x.attribute`` | call, attribute reference |
1357 +-----------------------------------------------+-------------------------------------+
1358 | ``(expressions...)``, | Binding or tuple display, |
1359 | ``[expressions...]``, | list display, |
1360 | ``{key:datum...}``, | dictionary display, |
1361 | ```expressions...``` | string conversion |
1362 +-----------------------------------------------+-------------------------------------+
1364 .. rubric:: Footnotes
1366 .. [#] In Python 2.3 and later releases, a list comprehension "leaks" the control
1367 variables of each ``for`` it contains into the containing scope. However, this
1368 behavior is deprecated, and relying on it will not work in Python 3.0
1370 .. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
1371 true numerically due to roundoff. For example, and assuming a platform on which
1372 a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
1373 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
1374 1e100``, which is numerically exactly equal to ``1e100``. Function :func:`fmod`
1375 in the :mod:`math` module returns a result whose sign matches the sign of the
1376 first argument instead, and so returns ``-1e-100`` in this case. Which approach
1377 is more appropriate depends on the application.
1379 .. [#] If x is very close to an exact integer multiple of y, it's possible for
1380 ``floor(x/y)`` to be one larger than ``(x-x%y)/y`` due to rounding. In such
1381 cases, Python returns the latter result, in order to preserve that
1382 ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.
1384 .. [#] While comparisons between unicode strings make sense at the byte
1385 level, they may be counter-intuitive to users. For example, the
1386 strings ``u"\u00C7"`` and ``u"\u0043\u0327"`` compare differently,
1387 even though they both represent the same unicode character (LATIN
1388 CAPTITAL LETTER C WITH CEDILLA). To compare strings in a human
1389 recognizable way, compare using :func:`unicodedata.normalize`.
1391 .. [#] The implementation computes this efficiently, without constructing lists or
1394 .. [#] Earlier versions of Python used lexicographic comparison of the sorted (key,
1395 value) lists, but this was very expensive for the common case of comparing for
1396 equality. An even earlier version of Python compared dictionaries by identity
1397 only, but this caused surprises because people expected to be able to test a
1398 dictionary for emptiness by comparing it to ``{}``.
1400 .. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
1401 descriptors, you may notice seemingly unusual behaviour in certain uses of
1402 the :keyword:`is` operator, like those involving comparisons between instance
1403 methods, or constants. Check their documentation for more info.
1405 .. [#] The power operator ``**`` binds less tightly than an arithmetic or
1406 bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.