| .. index:: |
| pair: list; display |
| pair: list; comprehensions |
| |
| A list display is a possibly empty series of expressions enclosed in square |
| brackets: |
| |
| .. productionlist:: |
n | test: `or_test` \| `lambda_form` |
n | list_display: "[" [`expression_list` | `list_comprehension`] "]" |
| testlist: `test` ( "," `test` )\* [ "," ] |
| list_comprehension: `expression` `list_for` |
| list_display: "[" [`listmaker`] "]" |
| list_for: "for" `target_list` "in" `old_expression_list` [`list_iter`] |
| listmaker: `expression` ( `list_for` \| ( "," `expression` )\* [","] ) |
| old_expression_list: `old_expression` [("," `old_expression`)+ [","]] |
| list_iter: `list_for` \| `list_if` |
| list_iter: `list_for` | `list_if` |
| list_for: "for" `expression_list` "in" `testlist` [`list_iter`] |
| list_if: "if" `test` [`list_iter`] |
| list_if: "if" `old_expression` [`list_iter`] |
| |
| .. index:: |
| pair: list; comprehensions |
| object: list |
| pair: empty; list |
| |
| A list display yields a new list object. Its contents are specified by |
n | providing either a list of expressions or a list comprehension. When a comma- |
n | providing either a list of expressions or a list comprehension. When a |
| separated list of expressions is supplied, its elements are evaluated from left |
| comma-separated list of expressions is supplied, its elements are evaluated from |
| to right and placed into the list object in that order. When a list |
| left to right and placed into the list object in that order. When a list |
| comprehension is supplied, it consists of a single expression followed by at |
| least one :keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if` |
| clauses. In this case, the elements of the new list are those that would be |
| produced by considering each of the :keyword:`for` or :keyword:`if` clauses a |
| block, nesting from left to right, and evaluating the expression to produce a |
| list element each time the innermost block is reached [#]_. |
| |
| |
| Generator expressions |
| --------------------- |
| |
| .. index:: pair: generator; expression |
| |
| A generator expression is a compact generator notation in parentheses: |
| |
| .. productionlist:: |
n | generator_expression: "(" `test` `genexpr_for` ")" |
n | generator_expression: "(" `expression` `genexpr_for` ")" |
| genexpr_for: "for" `expression_list` "in" `test` [`genexpr_iter`] |
| genexpr_for: "for" `target_list` "in" `or_test` [`genexpr_iter`] |
| genexpr_iter: `genexpr_for` \| `genexpr_if` |
| genexpr_iter: `genexpr_for` | `genexpr_if` |
| genexpr_if: "if" `test` [`genexpr_iter`] |
| genexpr_if: "if" `old_expression` [`genexpr_iter`] |
| |
n | .. index:: |
| object: generator |
| .. index:: object: generator |
| object: generator expression |
| |
n | A generator expression yields a new generator object. It consists of a single |
n | A generator expression yields a new generator object. It consists of a single |
| expression followed by at least one :keyword:`for` clause and zero or more |
| :keyword:`for` or :keyword:`if` clauses. The iterating values of the new |
| generator are those that would be produced by considering each of the |
| :keyword:`for` or :keyword:`if` clauses a block, nesting from left to right, and |
| evaluating the expression to yield a value that is reached the innermost block |
| for each iteration. |
| |
n | Variables used in the generator expression are evaluated lazily when the |
n | Variables used in the generator expression are evaluated lazily in a separate |
| :meth:`next` method is called for generator object (in the same fashion as |
| scope when the :meth:`next` method is called for the generator object (in the |
| normal generators). However, the leftmost :keyword:`for` clause is immediately |
| same fashion as for normal generators). However, the :keyword:`in` expression |
| of the leftmost :keyword:`for` clause is immediately evaluated in the current |
| evaluated so that error produced by it can be seen before any other possible |
| scope so that an error produced by it can be seen before any other possible |
| error in the code that handles the generator expression. Subsequent |
| error in the code that handles the generator expression. Subsequent |
| :keyword:`for` clauses cannot be evaluated immediately since they may depend on |
| :keyword:`for` and :keyword:`if` clauses cannot be evaluated immediately since |
| the previous :keyword:`for` loop. For example: ``(x*y for x in range(10) for y |
| they may depend on the previous :keyword:`for` loop. For example: |
| in bar(x))``. |
| ``(x*y for x in range(10) for y in bar(x))``. |
| |
| The parentheses can be omitted on calls with only one argument. See section |
| :ref:`calls` for the detail. |
| |
| |
| .. _dict: |
| |
| Dictionary displays |
| builtin: repr |
| builtin: str |
| |
| The built-in function :func:`repr` performs exactly the same conversion in its |
| argument as enclosing it in parentheses and reverse quotes does. The built-in |
| function :func:`str` performs a similar but more user-friendly conversion. |
| |
| |
n | .. _yieldexpr: |
| |
| Yield expressions |
| ----------------- |
| |
| .. index:: |
| keyword: yield |
| pair: yield; expression |
| pair: generator; function |
| |
| .. productionlist:: |
| yield_atom: "(" `yield_expression` ")" |
| yield_expression: "yield" [`expression_list`] |
| |
| .. versionadded:: 2.5 |
| |
| The :keyword:`yield` expression is only used when defining a generator function, |
| and can only be used in the body of a function definition. Using a |
| :keyword:`yield` expression in a function definition is sufficient to cause that |
| definition to create a generator function instead of a normal function. |
| |
| When a generator function is called, it returns an iterator known as a |
| generator. That generator then controls the execution of a generator function. |
| The execution starts when one of the generator's methods is called. At that |
| time, the execution proceeds to the first :keyword:`yield` expression, where it |
| is suspended again, returning the value of :token:`expression_list` to |
| generator's caller. By suspended we mean that all local state is retained, |
| including the current bindings of local variables, the instruction pointer, and |
| the internal evaluation stack. When the execution is resumed by calling one of |
| the generator's methods, the function can proceed exactly as if the |
| :keyword:`yield` expression was just another external call. The value of the |
| :keyword:`yield` expression after resuming depends on the method which resumed |
| the execution. |
| |
| .. index:: single: coroutine |
| |
| All of this makes generator functions quite similar to coroutines; they yield |
| multiple times, they have more than one entry point and their execution can be |
| suspended. The only difference is that a generator function cannot control |
| where should the execution continue after it yields; the control is always |
| transfered to the generator's caller. |
| |
| .. index:: object: generator |
| |
| The following generator's methods can be used to control the execution of a |
| generator function: |
| |
| .. index:: exception: StopIteration |
| |
| |
| .. method:: generator.next() |
| |
| Starts the execution of a generator function or resumes it at the last executed |
| :keyword:`yield` expression. When a generator function is resumed with a |
| :meth:`next` method, the current :keyword:`yield` expression always evaluates to |
| :const:`None`. The execution then continues to the next :keyword:`yield` |
| expression, where the generator is suspended again, and the value of the |
| :token:`expression_list` is returned to :meth:`next`'s caller. If the generator |
| exits without yielding another value, a :exc:`StopIteration` exception is |
| raised. |
| |
| |
| .. method:: generator.send(value) |
| |
| Resumes the execution and "sends" a value into the generator function. The |
| ``value`` argument becomes the result of the current :keyword:`yield` |
| expression. The :meth:`send` method returns the next value yielded by the |
| generator, or raises :exc:`StopIteration` if the generator exits without |
| yielding another value. When :meth:`send` is called to start the generator, it |
| must be called with :const:`None` as the argument, because there is no |
| :keyword:`yield` expression that could receive the value. |
| |
| |
| .. method:: generator.throw(type[, value[, traceback]]) |
| |
| Raises an exception of type ``type`` at the point where generator was paused, |
| and returns the next value yielded by the generator function. If the generator |
| exits without yielding another value, a :exc:`StopIteration` exception is |
| raised. If the generator function does not catch the passed-in exception, or |
| raises a different exception, then that exception propagates to the caller. |
| |
| .. index:: exception: GeneratorExit |
| |
| |
| .. method:: generator.close() |
| |
| Raises a :exc:`GeneratorExit` at the point where the generator function was |
| paused. If the generator function then raises :exc:`StopIteration` (by exiting |
| normally, or due to already being closed) or :exc:`GeneratorExit` (by not |
| catching the exception), close returns to its caller. If the generator yields a |
| value, a :exc:`RuntimeError` is raised. If the generator raises any other |
| exception, it is propagated to the caller. :meth:`close` does nothing if the |
| generator has already exited due to an exception or normal exit. |
| |
| Here is a simple example that demonstrates the behavior of generators and |
| generator functions:: |
| |
| >>> def echo(value=None): |
| ... print "Execution starts when 'next()' is called for the first time." |
| ... try: |
| ... while True: |
| ... try: |
| ... value = (yield value) |
| ... except Exception, e: |
| ... value = e |
| ... finally: |
| ... print "Don't forget to clean up when 'close()' is called." |
| ... |
| >>> generator = echo(1) |
| >>> print generator.next() |
| Execution starts when 'next()' is called for the first time. |
| 1 |
| >>> print generator.next() |
| None |
| >>> print generator.send(2) |
| 2 |
| >>> generator.throw(TypeError, "spam") |
| TypeError('spam',) |
| >>> generator.close() |
| Don't forget to clean up when 'close()' is called. |
| |
| |
| .. seealso:: |
| |
| :pep:`0342` - Coroutines via Enhanced Generators |
| The proposal to enhance the API and syntax of generators, making them usable as |
| simple coroutines. |
| |
| |
| .. _primaries: |
| |
| Primaries |
| ========= |
| |
| .. index:: single: primary |
| |
| Primaries represent the most tightly bound operations of the language. Their |
| syntax is: |
| |
| .. productionlist:: |
n | primary: `atom` \| `attributeref` \| `subscription` \| `slicing` \| `call` |
n | primary: `atom` | `attributeref` | `subscription` | `slicing` | `call` |
| |
| |
| .. _attribute-references: |
| |
| Attribute references |
| -------------------- |
| |
| .. index:: pair: attribute; reference |
| .. index:: single: call |
| |
| .. index:: object: callable |
| |
| A call calls a callable object (e.g., a function) with a possibly empty series |
| of arguments: |
| |
| .. productionlist:: |
n | call: `primary` "(" [`argument_list` [","]] ")" |
n | call: `primary` "(" [`argument_list` [","] |
| : | `expression` `genexpr_for`] ")" |
| argument_list: `positional_arguments` ["," `keyword_arguments`] |
n | : ["," "\*" `expression`] |
n | : ["," "*" `expression`] ["," `keyword_arguments`] |
| : ["," "\*\*" `expression`] |
| : ["," "**" `expression`] |
| : \| `keyword_arguments` ["," "\*" `expression`] |
| : | `keyword_arguments` ["," "*" `expression`] |
| : ["," "\*\*" `expression`] |
| : ["," "**" `expression`] |
| : \| "\*" `expression` ["," "\*\*" `expression`] |
| : | "*" `expression` ["," "*" `expression`] ["," "**" `expression`] |
| : \| "\*\*" `expression` |
| : | "**" `expression` |
| positional_arguments: `expression` ("," `expression`)\* |
| positional_arguments: `expression` ("," `expression`)* |
| keyword_arguments: `keyword_item` ("," `keyword_item`)\* |
| keyword_arguments: `keyword_item` ("," `keyword_item`)* |
| keyword_item: `identifier` "=" `expression` |
| |
| A trailing comma may be present after the positional and keyword arguments but |
| does not affect the semantics. |
| |
| The primary must evaluate to a callable object (user-defined functions, built-in |
| functions, methods of built-in objects, class objects, methods of class |
| instances, and certain class instances themselves are callable; extensions may |
| function definition. (Default values are calculated, once, when the function is |
| defined; thus, a mutable object such as a list or dictionary used as default |
| value will be shared by all calls that don't specify an argument value for the |
| corresponding slot; this should usually be avoided.) If there are any unfilled |
| slots for which no default value is specified, a :exc:`TypeError` exception is |
| raised. Otherwise, the list of filled slots is used as the argument list for |
| the call. |
| |
n | .. note:: |
| |
| An implementation may provide builtin functions whose positional parameters do |
| not have names, even if they are 'named' for the purpose of documentation, and |
| which therefore cannot be supplied by keyword. In CPython, this is the case for |
| functions implemented in C that use :cfunc:`PyArg_ParseTuple` to parse their |
| arguments. |
| |
| If there are more positional arguments than there are formal parameter slots, a |
| :exc:`TypeError` exception is raised, unless a formal parameter using the syntax |
| ``*identifier`` is present; in this case, that formal parameter receives a tuple |
| containing the excess positional arguments (or an empty tuple if there were no |
| excess positional arguments). |
| |
| If any keyword argument does not correspond to a formal parameter name, a |
| :exc:`TypeError` exception is raised, unless a formal parameter using the syntax |
| ``**identifier`` is present; in this case, that formal parameter receives a |
| dictionary containing the excess keyword arguments (using the keywords as keys |
| and the argument values as corresponding values), or a (new) empty dictionary if |
| there were no excess keyword arguments. |
| |
| If the syntax ``*expression`` appears in the function call, ``expression`` must |
| evaluate to a sequence. Elements from this sequence are treated as if they were |
n | additional positional arguments; if there are postional arguments *x1*,...,*xN* |
n | additional positional arguments; if there are positional arguments *x1*,..., |
| , and ``expression`` evaluates to a sequence *y1*,...,*yM*, this is equivalent |
| *xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*, this is |
| to a call with M+N positional arguments *x1*,...,*xN*,*y1*,...,*yM*. |
| equivalent to a call with M+N positional arguments *x1*, ..., *xN*, *y1*, ..., |
| *yM*. |
| |
n | A consequence of this is that although the ``*expression`` syntax appears |
n | A consequence of this is that although the ``*expression`` syntax may appear |
| *after* any keyword arguments, it is processed *before* the keyword arguments |
| *after* some keyword arguments, it is processed *before* the keyword arguments |
| (and the ``**expression`` argument, if any -- see below). So:: |
| |
| >>> def f(a, b): |
| ... print a, b |
| ... |
| >>> f(b=1, *(2,)) |
| 2 1 |
| >>> f(a=1, *(2,)) |
| Shifting operations |
| =================== |
| |
| .. index:: pair: shifting; operation |
| |
| The shifting operations have lower priority than the arithmetic operations: |
| |
| .. productionlist:: |
n | shift_expr: `a_expr` \| `shift_expr` ( "<<" \| ">>" ) `a_expr` |
n | shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr` |
| |
| These operators accept plain or long integers as arguments. The arguments are |
| converted to a common type. They shift the first argument to the left or right |
| by the number of bits given by the second argument. |
| |
| .. index:: exception: ValueError |
| |
n | A right shift by *n* bits is defined as division by ``pow(2,n)``. A left shift |
n | A right shift by *n* bits is defined as division by ``pow(2, n)``. A left shift |
| by *n* bits is defined as multiplication with ``pow(2,n)``; for plain integers |
| by *n* bits is defined as multiplication with ``pow(2, n)``. Negative shift |
| there is no overflow check so in that case the operation drops bits and flips |
| the sign if the result is not less than ``pow(2,31)`` in absolute value. |
| Negative shift counts raise a :exc:`ValueError` exception. |
| counts raise a :exc:`ValueError` exception. |
| |
| |
| .. _bitwise: |
| |
n | Binary bit-wise operations |
n | Binary bitwise operations |
| ========================== |
| ========================= |
| |
n | .. index:: triple: binary; bit-wise; operation |
n | .. index:: triple: binary; bitwise; operation |
| |
| Each of the three bitwise operations has a different priority level: |
| |
| .. productionlist:: |
n | and_expr: `shift_expr` \| `and_expr` "&" `shift_expr` |
n | and_expr: `shift_expr` | `and_expr` "&" `shift_expr` |
| xor_expr: `and_expr` \| `xor_expr` "^" `and_expr` |
| xor_expr: `and_expr` | `xor_expr` "^" `and_expr` |
| or_expr: `xor_expr` \| `or_expr` "\|" `xor_expr` |
| or_expr: `xor_expr` | `or_expr` "|" `xor_expr` |
| |
n | .. index:: pair: bit-wise; and |
n | .. index:: pair: bitwise; and |
| |
| The ``&`` operator yields the bitwise AND of its arguments, which must be plain |
| or long integers. The arguments are converted to a common type. |
| |
| .. index:: |
n | pair: bit-wise; xor |
n | pair: bitwise; xor |
| pair: exclusive; or |
| |
| The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which |
| must be plain or long integers. The arguments are converted to a common type. |
| |
| .. index:: |
n | pair: bit-wise; or |
n | pair: bitwise; or |
| pair: inclusive; or |
| |
| The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which |
| must be plain or long integers. The arguments are converted to a common type. |
| |
| |
| .. _comparisons: |
n | .. _is: |
| .. _isnot: |
| .. _in: |
| .. _notin: |
| |
| Comparisons |
| =========== |
| |
| .. index:: single: comparison |
| |
| .. index:: pair: C; language |
| |
| Unlike C, all comparison operations in Python have the same priority, which is |
| lower than that of any arithmetic, shifting or bitwise operation. Also unlike |
| C, expressions like ``a < b < c`` have the interpretation that is conventional |
| in mathematics: |
| |
| .. productionlist:: |
n | comparison: `or_expr` ( `comp_operator` `or_expr` )\* |
n | comparison: `or_expr` ( `comp_operator` `or_expr` )* |
| comp_operator: "<" \| ">" \| "==" \| ">=" \| "<=" \| "<>" \| "!=" |
| comp_operator: "<" | ">" | "==" | ">=" | "<=" | "<>" | "!=" |
| : \| "is" ["not"] \| ["not"] "in" |
| : | "is" ["not"] | ["not"] "in" |
| |
| Comparisons yield boolean values: ``True`` or ``False``. |
| |
| .. index:: pair: chaining; comparisons |
| |
| Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to |
| ``x < y and y <= z``, except that ``y`` is evaluated only once (but in both |
| cases ``z`` is not evaluated at all when ``x < y`` is found to be false). |
| |
n | Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *opa*, *opb*, ..., |
n | Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ..., |
| *opy* are comparison operators, then *a opa b opb c* ...*y opy z* is equivalent |
| *opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent |
| to *a opa b* :keyword:`and` *b opb c* :keyword:`and` ... *y opy z*, except that |
| to ``a op1 b and b op2 c and ... y opN z``, except that each expression is |
| each expression is evaluated at most once. |
| evaluated at most once. |
| |
n | Note that *a opa b opb c* doesn't imply any kind of comparison between *a* and |
n | Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and |
| *c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not |
| pretty). |
| |
| The forms ``<>`` and ``!=`` are equivalent; for consistency with C, ``!=`` is |
| preferred; where ``!=`` is mentioned below ``<>`` is also accepted. The ``<>`` |
| spelling is considered obsolescent. |
| |
| The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the |
| lists compare equal. [#]_ Outcomes other than equality are resolved |
| consistently, but are not otherwise defined. [#]_ |
| |
| * Most other objects of builtin types compare unequal unless they are the same |
| object; the choice whether one object is considered smaller or larger than |
| another one is made arbitrarily but consistently within one execution of a |
| program. |
| |
n | The operators :keyword:`in` and :keyword:`not in` test for set membership. ``x |
n | The operators :keyword:`in` and :keyword:`not in` test for collection |
| in s`` evaluates to true if *x* is a member of the set *s*, and false otherwise. |
| membership. ``x in s`` evaluates to true if *x* is a member of the collection |
| ``x not in s`` returns the negation of ``x in s``. The set membership test has |
| *s*, and false otherwise. ``x not in s`` returns the negation of ``x in s``. |
| traditionally been bound to sequences; an object is a member of a set if the set |
| The collection membership test has traditionally been bound to sequences; an |
| is a sequence and contains an element equal to that object. However, it is |
| object is a member of a collection if the collection is a sequence and contains |
| an element equal to that object. However, it make sense for many other object |
| possible for an object to support membership tests without being a sequence. In |
| types to support membership tests without being a sequence. In particular, |
| particular, dictionaries support membership testing as a nicer way of spelling |
| dictionaries (for keys) and sets support membership testing. |
| ``key in dict``; other mapping types may follow suit. |
| |
| For the list and tuple types, ``x in y`` is true if and only if there exists an |
| index *i* such that ``x == y[i]`` is true. |
| |
| For the Unicode and string types, ``x in y`` is true if and only if *x* is a |
| substring of *y*. An equivalent test is ``y.find(x) != -1``. Note, *x* and *y* |
| need not be the same type; consequently, ``u'ab' in 'abc'`` will return |
| ``True``. Empty strings are always considered to be a substring of any other |
| |
| .. index:: |
| operator: is |
| operator: is not |
| pair: identity; test |
| |
| The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x |
| is y`` is true if and only if *x* and *y* are the same object. ``x is not y`` |
n | yields the inverse truth value. |
n | yields the inverse truth value. [#]_ |
| |
| |
| .. _booleans: |
n | .. _and: |
| .. _or: |
| .. _not: |
| |
| Boolean operations |
| ================== |
| |
n | .. index:: |
| pair: Conditional; expression |
| .. index:: pair: Boolean; operation |
| pair: Boolean; operation |
| |
| Boolean operations have the lowest priority of all Python operations: |
| |
| .. productionlist:: |
n | expression: `or_test` [`if` `or_test` `else` `test`] \| `lambda_form` |
n | expression: `conditional_expression` | `lambda_form` |
| old_expression: `or_test` | `old_lambda_form` |
| conditional_expression: `or_test` ["if" `or_test` "else" `expression`] |
| or_test: `and_test` \| `or_test` "or" `and_test` |
| or_test: `and_test` | `or_test` "or" `and_test` |
| and_test: `not_test` \| `and_test` "and" `not_test` |
| and_test: `not_test` | `and_test` "and" `not_test` |
| not_test: `comparison` \| "not" `not_test` |
| not_test: `comparison` | "not" `not_test` |
| |
| In the context of Boolean operations, and also when expressions are used by |
| control flow statements, the following values are interpreted as false: |
| ``False``, ``None``, numeric zero of all types, and empty strings and containers |
| (including strings, tuples, lists, dictionaries, sets and frozensets). All |
n | other values are interpreted as true. |
n | other values are interpreted as true. (See the :meth:`~object.__nonzero__` |
| special method for a way to change this.) |
| |
| .. index:: operator: not |
| |
| The operator :keyword:`not` yields ``True`` if its argument is false, ``False`` |
| otherwise. |
| |
| The expression ``x if C else y`` first evaluates *C* (*not* *x*); if *C* is |
| true, *x* is evaluated and its value is returned; otherwise, *y* is evaluated |
| |
| In the following lines, expressions will be evaluated in the arithmetic order of |
| their suffixes:: |
| |
| expr1, expr2, expr3, expr4 |
| (expr1, expr2, expr3, expr4) |
| {expr1: expr2, expr3: expr4} |
| expr1 + expr2 * (expr3 - expr4) |
n | func(expr1, expr2, *expr3, **expr4) |
n | expr1(expr2, expr3, *expr4, **expr5) |
| expr3, expr4 = expr1, expr2 |
| |
| |
n | .. _summary: |
n | .. _operator-summary: |
| |
| Summary |
| ======= |
| |
| .. index:: pair: operator; precedence |
| |
| The following table summarizes the operator precedences in Python, from lowest |
| precedence (least binding) to highest precedence (most binding). Operators in |
| the same box have the same precedence. Unless the syntax is explicitly given, |
| operators are binary. Operators in the same box group left to right (except for |
| comparisons, including tests, which all have the same precedence and chain from |
n | left to right --- see section :ref:`comparisons` -- and exponentiation, which |
n | left to right --- see section :ref:`comparisons` --- and exponentiation, which |
| groups from right to left). |
| |
| +-----------------------------------------------+-------------------------------------+ |
| | Operator | Description | |
| +===============================================+=====================================+ |
| | :keyword:`lambda` | Lambda expression | |
| +-----------------------------------------------+-------------------------------------+ |
| | :keyword:`or` | Boolean OR | |
| +-----------------------------------------------+-------------------------------------+ |
| | :keyword:`and` | Boolean AND | |
| +-----------------------------------------------+-------------------------------------+ |
| | :keyword:`not` *x* | Boolean NOT | |
| +-----------------------------------------------+-------------------------------------+ |
n | | :keyword:`in`, :keyword:`not` :keyword:`in` | Membership tests | |
n | | :keyword:`in`, :keyword:`not` :keyword:`in`, | Comparisons, including membership | |
| +-----------------------------------------------+-------------------------------------+ |
| | :keyword:`is`, :keyword:`is not` | Identity tests | |
| | :keyword:`is`, :keyword:`is not`, ``<``, | tests and identity tests, | |
| +-----------------------------------------------+-------------------------------------+ |
| | ``<``, ``<=``, ``>``, ``>=``, ``<>``, ``!=``, | Comparisons | |
| | ``<=``, ``>``, ``>=``, ``<>``, ``!=``, ``==`` | | |
| | ``==`` | | |
| +-----------------------------------------------+-------------------------------------+ |
| | ``|`` | Bitwise OR | |
| +-----------------------------------------------+-------------------------------------+ |
| | ``^`` | Bitwise XOR | |
| +-----------------------------------------------+-------------------------------------+ |
| | ``&`` | Bitwise AND | |
| +-----------------------------------------------+-------------------------------------+ |
| | ``<<``, ``>>`` | Shifts | |
| +-----------------------------------------------+-------------------------------------+ |
| | ``+``, ``-`` | Addition and subtraction | |
| +-----------------------------------------------+-------------------------------------+ |
n | | ``*``, ``/``, ``%`` | Multiplication, division, remainder | |
n | | ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder | |
| +-----------------------------------------------+-------------------------------------+ |
n | | ``+x``, ``-x`` | Positive, negative | |
n | | ``+x``, ``-x``, ``~x`` | Positive, negative, bitwise NOT | |
| +-----------------------------------------------+-------------------------------------+ |
n | | ``~x`` | Bitwise not | |
| +-----------------------------------------------+-------------------------------------+ |
| | ``**`` | Exponentiation | |
| | ``**`` | Exponentiation [#]_ | |
| +-----------------------------------------------+-------------------------------------+ |
n | | ``x.attribute`` | Attribute reference | |
n | | ``x[index]``, ``x[index:index]``, | Subscription, slicing, | |
| | ``x(arguments...)``, ``x.attribute`` | call, attribute reference | |
| +-----------------------------------------------+-------------------------------------+ |
n | | ``x[index]`` | Subscription | |
| +-----------------------------------------------+-------------------------------------+ |
| | ``x[index:index]`` | Slicing | |
| +-----------------------------------------------+-------------------------------------+ |
| | ``f(arguments...)`` | Function call | |
| +-----------------------------------------------+-------------------------------------+ |
| | ``(expressions...)`` | Binding or tuple display | |
| | ``(expressions...)``, | Binding or tuple display, | |
| +-----------------------------------------------+-------------------------------------+ |
| | ``[expressions...]`` | List display | |
| | ``[expressions...]``, | list display, | |
| +-----------------------------------------------+-------------------------------------+ |
| | ``{key:datum...}`` | Dictionary display | |
| | ``{key:datum...}``, | dictionary display, | |
| +-----------------------------------------------+-------------------------------------+ |
| | ```expressions...``\ ` | String conversion | |
| | ```expressions...``` | string conversion | |
| +-----------------------------------------------+-------------------------------------+ |
| |
| .. rubric:: Footnotes |
| |
n | .. [#] In Python 2.3, a list comprehension "leaks" the control variables of each |
n | .. [#] In Python 2.3 and later releases, a list comprehension "leaks" the control |
| ``for`` it contains into the containing scope. However, this behavior is |
| variables of each ``for`` it contains into the containing scope. However, this |
| deprecated, and relying on it will not work once this bug is fixed in a future |
| behavior is deprecated, and relying on it will not work in Python 3.0 |
| release |
| |
| .. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be |
| true numerically due to roundoff. For example, and assuming a platform on which |
| a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 % |
| 1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 + |
| 1e100``, which is numerically exactly equal to ``1e100``. Function :func:`fmod` |
| in the :mod:`math` module returns a result whose sign matches the sign of the |
| first argument instead, and so returns ``-1e-100`` in this case. Which approach |
| is more appropriate depends on the application. |
| |
| .. [#] If x is very close to an exact integer multiple of y, it's possible for |
| ``floor(x/y)`` to be one larger than ``(x-x%y)/y`` due to rounding. In such |
| cases, Python returns the latter result, in order to preserve that |
| ``divmod(x,y)[0] * y + x % y`` be very close to ``x``. |
| |
n | .. [#] While comparisons between unicode strings make sense at the byte |
| level, they may be counter-intuitive to users. For example, the |
| strings ``u"\u00C7"`` and ``u"\u0043\u0327"`` compare differently, |
| even though they both represent the same unicode character (LATIN |
| CAPTITAL LETTER C WITH CEDILLA). To compare strings in a human |
| recognizable way, compare using :func:`unicodedata.normalize`. |
| |
| .. [#] The implementation computes this efficiently, without constructing lists or |
| sorting. |
| |
| .. [#] Earlier versions of Python used lexicographic comparison of the sorted (key, |
| value) lists, but this was very expensive for the common case of comparing for |
| equality. An even earlier version of Python compared dictionaries by identity |
| only, but this caused surprises because people expected to be able to test a |
| dictionary for emptiness by comparing it to ``{}``. |
| |
t | .. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of |
| descriptors, you may notice seemingly unusual behaviour in certain uses of |
| the :keyword:`is` operator, like those involving comparisons between instance |
| methods, or constants. Check their documentation for more info. |
| |
| .. [#] The power operator ``**`` binds less tightly than an arithmetic or |
| bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``. |