Added 'list_only' option (and modified 'run()' to respect it).
[python/dscho.git] / Doc / ref / ref5.tex
blob72a2053d612d763980e4a4e1b25cea5963e9201c
1 \chapter{Expressions\label{expressions}}
2 \index{expression}
4 This chapter explains the meaning of the elements of expressions in
5 Python.
7 \strong{Syntax Notes:} In this and the following chapters, extended
8 BNF\index{BNF} notation will be used to describe syntax, not lexical
9 analysis. When (one alternative of) a syntax rule has the form
11 \begin{verbatim}
12 name: othername
13 \end{verbatim}
15 and no semantics are given, the semantics of this form of \code{name}
16 are the same as for \code{othername}.
17 \index{syntax}
19 \section{Arithmetic conversions\label{conversions}}
20 \indexii{arithmetic}{conversion}
22 When a description of an arithmetic operator below uses the phrase
23 ``the numeric arguments are converted to a common type,'' the
24 arguments are coerced using the coercion rules listed at the end of
25 chapter 3. If both arguments are standard numeric types, the
26 following coercions are applied:
28 \begin{itemize}
29 \item If either argument is a complex number, the other is converted
30 to complex;
31 \item otherwise, if either argument is a floating point number,
32 the other is converted to floating point;
33 \item otherwise, if either argument is a long integer,
34 the other is converted to long integer;
35 \item otherwise, both must be plain integers and no conversion
36 is necessary.
37 \end{itemize}
39 Some additional rules apply for certain operators (e.g., a string left
40 argument to the `\%' operator). Extensions can define their own
41 coercions.
44 \section{Atoms\label{atoms}}
45 \index{atom}
47 Atoms are the most basic elements of expressions. The simplest atoms
48 are identifiers or literals. Forms enclosed in
49 reverse quotes or in parentheses, brackets or braces are also
50 categorized syntactically as atoms. The syntax for atoms is:
52 \begin{verbatim}
53 atom: identifier | literal | enclosure
54 enclosure: parenth_form|list_display|dict_display|string_conversion
55 \end{verbatim}
57 \subsection{Identifiers (Names)\label{atom-identifiers}}
58 \index{name}
59 \index{identifier}
61 An identifier occurring as an atom is a reference to a local, global
62 or built-in name binding. If a name is assigned to anywhere in a code
63 block (even in unreachable code), and is not mentioned in a
64 \keyword{global} statement in that code block, then it refers to a local
65 name throughout that code block. When it is not assigned to anywhere
66 in the block, or when it is assigned to but also explicitly listed in
67 a \keyword{global} statement, it refers to a global name if one exists,
68 else to a built-in name (and this binding may dynamically change).
69 \indexii{name}{binding}
70 \index{code block}
71 \stindex{global}
72 \indexii{built-in}{name}
73 \indexii{global}{name}
75 When the name is bound to an object, evaluation of the atom yields
76 that object. When a name is not bound, an attempt to evaluate it
77 raises a \exception{NameError} exception.
78 \exindex{NameError}
80 \strong{Private name mangling:}%
81 \indexii{name}{mangling}%
82 \indexii{private}{names}%
83 when an identifier that textually occurs in a class definition begins
84 with two or more underscore characters and does not end in two or more
85 underscores, it is considered a \dfn{private name} of that class.
86 Private names are transformed to a longer form before code is
87 generated for them. The transformation inserts the class name in
88 front of the name, with leading underscores removed, and a single
89 underscore inserted in front of the class name. For example, the
90 identifier \code{__spam} occurring in a class named \code{Ham} will be
91 transformed to \code{_Ham__spam}. This transformation is independent
92 of the syntactical context in which the identifier is used. If the
93 transformed name is extremely long (longer than 255 characters),
94 implementation defined truncation may happen. If the class name
95 consists only of underscores, no transformation is done.
97 \subsection{Literals\label{atom-literals}}
98 \index{literal}
100 Python supports string literals and various numeric literals:
102 \begin{verbatim}
103 literal: stringliteral | integer | longinteger | floatnumber | imagnumber
104 \end{verbatim}
106 Evaluation of a literal yields an object of the given type (string,
107 integer, long integer, floating point number, complex number) with the
108 given value. The value may be approximated in the case of floating
109 point and imaginary (complex) literals. See section \ref{literals}
110 for details.
112 All literals correspond to immutable data types, and hence the
113 object's identity is less important than its value. Multiple
114 evaluations of literals with the same value (either the same
115 occurrence in the program text or a different occurrence) may obtain
116 the same object or a different object with the same value.
117 \indexiii{immutable}{data}{type}
118 \indexii{immutable}{objects}
120 \subsection{Parenthesized forms\label{parenthesized}}
121 \index{parenthesized form}
123 A parenthesized form is an optional expression list enclosed in
124 parentheses:
126 \begin{verbatim}
127 parenth_form: "(" [expression_list] ")"
128 \end{verbatim}
130 A parenthesized expression list yields whatever that expression list
131 yields: if the list contains at least one comma, it yields a tuple;
132 otherwise, it yields the single expression that makes up the
133 expression list.
135 An empty pair of parentheses yields an empty tuple object. Since
136 tuples are immutable, the rules for literals apply (i.e., two
137 occurrences of the empty tuple may or may not yield the same object).
138 \indexii{empty}{tuple}
140 Note that tuples are not formed by the parentheses, but rather by use
141 of the comma operator. The exception is the empty tuple, for which
142 parentheses \emph{are} required --- allowing unparenthesized ``nothing''
143 in expressions would cause ambiguities and allow common typos to
144 pass uncaught.
145 \index{comma}
146 \indexii{tuple}{display}
148 \subsection{List displays\label{lists}}
149 \indexii{list}{display}
151 A list display is a possibly empty series of expressions enclosed in
152 square brackets:
154 \begin{verbatim}
155 list_display: "[" [expression_list] "]"
156 \end{verbatim}
158 A list display yields a new list object. If it has no expression
159 list, the list object has no items. Otherwise, the elements of the
160 expression list are evaluated from left to right and inserted in the
161 list object in that order.
162 \obindex{list}
163 \indexii{empty}{list}
165 \subsection{Dictionary displays\label{dict}}
166 \indexii{dictionary}{display}
168 A dictionary display is a possibly empty series of key/datum pairs
169 enclosed in curly braces:
170 \index{key}
171 \index{datum}
172 \index{key/datum pair}
174 \begin{verbatim}
175 dict_display: "{" [key_datum_list] "}"
176 key_datum_list: key_datum ("," key_datum)* [","]
177 key_datum: expression ":" expression
178 \end{verbatim}
180 A dictionary display yields a new dictionary object.
181 \obindex{dictionary}
183 The key/datum pairs are evaluated from left to right to define the
184 entries of the dictionary: each key object is used as a key into the
185 dictionary to store the corresponding datum.
187 Restrictions on the types of the key values are listed earlier in
188 section \ref{types}. (To summarize,the key type should be hashable,
189 which excludes all mutable objects.) Clashes between duplicate keys
190 are not detected; the last datum (textually rightmost in the display)
191 stored for a given key value prevails.
192 \indexii{immutable}{objects}
194 \subsection{String conversions\label{string-conversions}}
195 \indexii{string}{conversion}
196 \indexii{reverse}{quotes}
197 \indexii{backward}{quotes}
198 \index{back-quotes}
200 A string conversion is an expression list enclosed in reverse (a.k.a.
201 backward) quotes:
203 \begin{verbatim}
204 string_conversion: "`" expression_list "`"
205 \end{verbatim}
207 A string conversion evaluates the contained expression list and
208 converts the resulting object into a string according to rules
209 specific to its type.
211 If the object is a string, a number, \code{None}, or a tuple, list or
212 dictionary containing only objects whose type is one of these, the
213 resulting string is a valid Python expression which can be passed to
214 the built-in function \function{eval()} to yield an expression with the
215 same value (or an approximation, if floating point numbers are
216 involved).
218 (In particular, converting a string adds quotes around it and converts
219 ``funny'' characters to escape sequences that are safe to print.)
221 It is illegal to attempt to convert recursive objects (e.g., lists or
222 dictionaries that contain a reference to themselves, directly or
223 indirectly.)
224 \obindex{recursive}
226 The built-in function \function{repr()} performs exactly the same
227 conversion in its argument as enclosing it in parentheses and reverse
228 quotes does. The built-in function \function{str()} performs a
229 similar but more user-friendly conversion.
230 \bifuncindex{repr}
231 \bifuncindex{str}
233 \section{Primaries\label{primaries}}
234 \index{primary}
236 Primaries represent the most tightly bound operations of the language.
237 Their syntax is:
239 \begin{verbatim}
240 primary: atom | attributeref | subscription | slicing | call
241 \end{verbatim}
243 \subsection{Attribute references\label{attribute-references}}
244 \indexii{attribute}{reference}
246 An attribute reference is a primary followed by a period and a name:
248 \begin{verbatim}
249 attributeref: primary "." identifier
250 \end{verbatim}
252 The primary must evaluate to an object of a type that supports
253 attribute references, e.g., a module or a list. This object is then
254 asked to produce the attribute whose name is the identifier. If this
255 attribute is not available, the exception
256 \exception{AttributeError}\exindex{AttributeError} is raised.
257 Otherwise, the type and value of the object produced is determined by
258 the object. Multiple evaluations of the same attribute reference may
259 yield different objects.
260 \obindex{module}
261 \obindex{list}
263 \subsection{Subscriptions\label{subscriptions}}
264 \index{subscription}
266 A subscription selects an item of a sequence (string, tuple or list)
267 or mapping (dictionary) object:
268 \obindex{sequence}
269 \obindex{mapping}
270 \obindex{string}
271 \obindex{tuple}
272 \obindex{list}
273 \obindex{dictionary}
274 \indexii{sequence}{item}
276 \begin{verbatim}
277 subscription: primary "[" expression_list "]"
278 \end{verbatim}
280 The primary must evaluate to an object of a sequence or mapping type.
282 If the primary is a mapping, the expression list must evaluate to an
283 object whose value is one of the keys of the mapping, and the
284 subscription selects the value in the mapping that corresponds to that
285 key. (The expression list is a tuple except if it has exactly one
286 item.)
288 If the primary is a sequence, the expression (list) must evaluate to a
289 plain integer. If this value is negative, the length of the sequence
290 is added to it (so that, e.g., \code{x[-1]} selects the last item of
291 \code{x}.) The resulting value must be a nonnegative integer less
292 than the number of items in the sequence, and the subscription selects
293 the item whose index is that value (counting from zero).
295 A string's items are characters. A character is not a separate data
296 type but a string of exactly one character.
297 \index{character}
298 \indexii{string}{item}
300 \subsection{Slicings\label{slicings}}
301 \index{slicing}
302 \index{slice}
304 A slicing selects a range of items in a sequence object (e.g., a
305 string, tuple or list). Slicings may be used as expressions or as
306 targets in assignment or del statements. The syntax for a slicing:
307 \obindex{sequence}
308 \obindex{string}
309 \obindex{tuple}
310 \obindex{list}
312 \begin{verbatim}
313 slicing: simple_slicing | extended_slicing
314 simple_slicing: primary "[" short_slice "]"
315 extended_slicing: primary "[" slice_list "]"
316 slice_list: slice_item ("," slice_item)* [","]
317 slice_item: expression | proper_slice | ellipsis
318 proper_slice: short_slice | long_slice
319 short_slice: [lower_bound] ":" [upper_bound]
320 long_slice: short_slice ":" [stride]
321 lower_bound: expression
322 upper_bound: expression
323 stride: expression
324 ellipsis: "..."
325 \end{verbatim}
327 There is ambiguity in the formal syntax here: anything that looks like
328 an expression list also looks like a slice list, so any subscription
329 can be interpreted as a slicing. Rather than further complicating the
330 syntax, this is disambiguated by defining that in this case the
331 interpretation as a subscription takes priority over the
332 interpretation as a slicing (this is the case if the slice list
333 contains no proper slice nor ellipses). Similarly, when the slice
334 list has exactly one short slice and no trailing comma, the
335 interpretation as a simple slicing takes priority over that as an
336 extended slicing.\indexii{extended}{slicing}
338 The semantics for a simple slicing are as follows. The primary must
339 evaluate to a sequence object. The lower and upper bound expressions,
340 if present, must evaluate to plain integers; defaults are zero and the
341 sequence's length, respectively. If either bound is negative, the
342 sequence's length is added to it. The slicing now selects all items
343 with index \var{k} such that
344 \code{\var{i} <= \var{k} < \var{j}} where \var{i}
345 and \var{j} are the specified lower and upper bounds. This may be an
346 empty sequence. It is not an error if \var{i} or \var{j} lie outside the
347 range of valid indexes (such items don't exist so they aren't
348 selected).
350 The semantics for an extended slicing are as follows. The primary
351 must evaluate to a mapping object, and it is indexed with a key that
352 is constructed from the slice list, as follows. If the slice list
353 contains at least one comma, the key is a tuple containing the
354 conversion of the slice items; otherwise, the conversion of the lone
355 slice item is the key. The conversion of a slice item that is an
356 expression is that expression. The conversion of an ellipsis slice
357 item is the built-in \code{Ellipsis} object. The conversion of a
358 proper slice is a slice object (see section \ref{types}) whose
359 \member{start}, \member{stop} and \member{step} attributes are the
360 values of the expressions given as lower bound, upper bound and
361 stride, respectively, substituting \code{None} for missing
362 expressions.
363 \withsubitem{(slice object attribute)}{\ttindex{start}
364 \ttindex{stop}\ttindex{step}}
366 \subsection{Calls\label{calls}}
367 \index{call}
369 A call calls a callable object (e.g., a function) with a possibly empty
370 series of arguments:
371 \obindex{callable}
373 \begin{verbatim}
374 call: primary "(" [argument_list [","]] ")"
375 argument_list: positional_arguments ["," keyword_arguments]
376 | keyword_arguments
377 positional_arguments: expression ("," expression)*
378 keyword_arguments: keyword_item ("," keyword_item)*
379 keyword_item: identifier "=" expression
380 \end{verbatim}
382 A trailing comma may be present after an argument list but does not
383 affect the semantics.
385 The primary must evaluate to a callable object (user-defined
386 functions, built-in functions, methods of built-in objects, class
387 objects, methods of class instances, and certain class instances
388 themselves are callable; extensions may define additional callable
389 object types). All argument expressions are evaluated before the call
390 is attempted. Please refer to section \ref{function} for the syntax
391 of formal parameter lists.
393 If keyword arguments are present, they are first converted to
394 positional arguments, as follows. First, a list of unfilled slots is
395 created for the formal parameters. If there are N positional
396 arguments, they are placed in the first N slots. Next, for each
397 keyword argument, the identifier is used to determine the
398 corresponding slot (if the identifier is the same as the first formal
399 parameter name, the first slot is used, and so on). If the slot is
400 already filled, a \exception{TypeError} exception is raised.
401 Otherwise, the value of the argument is placed in the slot, filling it
402 (even if the expression is \code{None}, it fills the slot). When all
403 arguments have been processed, the slots that are still unfilled are
404 filled with the corresponding default value from the function
405 definition. (Default values are calculated, once, when the function
406 is defined; thus, a mutable object such as a list or dictionary used
407 as default value will be shared by all calls that don't specify an
408 argument value for the corresponding slot; this should usually be
409 avoided.) If there are any unfilled slots for which no default value
410 is specified, a \exception{TypeError} exception is raised. Otherwise,
411 the list of filled slots is used as the argument list for the call.
413 If there are more positional arguments than there are formal parameter
414 slots, a \exception{TypeError} exception is raised, unless a formal
415 parameter using the syntax \samp{*identifier} is present; in this
416 case, that formal parameter receives a tuple containing the excess
417 positional arguments (or an empty tuple if there were no excess
418 positional arguments).
420 If any keyword argument does not correspond to a formal parameter
421 name, a \exception{TypeError} exception is raised, unless a formal
422 parameter using the syntax \samp{**identifier} is present; in this
423 case, that formal parameter receives a dictionary containing the
424 excess keyword arguments (using the keywords as keys and the argument
425 values as corresponding values), or a (new) empty dictionary if there
426 were no excess keyword arguments.
428 Formal parameters using the syntax \samp{*identifier} or
429 \samp{**identifier} cannot be used as positional argument slots or
430 as keyword argument names. Formal parameters using the syntax
431 \samp{(sublist)} cannot be used as keyword argument names; the
432 outermost sublist corresponds to a single unnamed argument slot, and
433 the argument value is assigned to the sublist using the usual tuple
434 assignment rules after all other parameter processing is done.
436 A call always returns some value, possibly \code{None}, unless it
437 raises an exception. How this value is computed depends on the type
438 of the callable object.
440 If it is---
442 \begin{description}
444 \item[a user-defined function:] The code block for the function is
445 executed, passing it the argument list. The first thing the code
446 block will do is bind the formal parameters to the arguments; this is
447 described in section \ref{function}. When the code block executes a
448 \keyword{return} statement, this specifies the return value of the
449 function call.
450 \indexii{function}{call}
451 \indexiii{user-defined}{function}{call}
452 \obindex{user-defined function}
453 \obindex{function}
455 \item[a built-in function or method:] The result is up to the
456 interpreter; see the library reference manual for the descriptions of
457 built-in functions and methods.
458 \indexii{function}{call}
459 \indexii{built-in function}{call}
460 \indexii{method}{call}
461 \indexii{built-in method}{call}
462 \obindex{built-in method}
463 \obindex{built-in function}
464 \obindex{method}
465 \obindex{function}
467 \item[a class object:] A new instance of that class is returned.
468 \obindex{class}
469 \indexii{class object}{call}
471 \item[a class instance method:] The corresponding user-defined
472 function is called, with an argument list that is one longer than the
473 argument list of the call: the instance becomes the first argument.
474 \obindex{class instance}
475 \obindex{instance}
476 \indexii{class instance}{call}
478 \item[a class instance:] The class must define a \method{__call__()}
479 method; the effect is then the same as if that method was called.
480 \indexii{instance}{call}
481 \withsubitem{(object method)}{\ttindex{__call__()}}
483 \end{description}
486 \section{The power operator\label{power}}
488 The power operator binds more tightly than unary operators on its
489 left; it binds less tightly than unary operators on its right. The
490 syntax is:
492 \begin{verbatim}
493 power: primary ["**" u_expr]
494 \end{verbatim}
496 Thus, in an unparenthesized sequence of power and unary operators, the
497 operators are evaluated from right to left (this does not constrain
498 the evaluation order for the operands).
500 The power operator has the same semantics as the built-in
501 \function{pow()} function, when called with two arguments: it yields
502 its left argument raised to the power of its right argument. The
503 numeric arguments are first converted to a common type. The result
504 type is that of the arguments after coercion; if the result is not
505 expressible in that type (as in raising an integer to a negative
506 power, or a negative floating point number to a broken power), a
507 \exception{TypeError} exception is raised.
510 \section{Unary arithmetic operations\label{unary}}
511 \indexiii{unary}{arithmetic}{operation}
512 \indexiii{unary}{bit-wise}{operation}
514 All unary arithmetic (and bit-wise) operations have the same priority:
516 \begin{verbatim}
517 u_expr: power | "-" u_expr | "+" u_expr | "~" u_expr
518 \end{verbatim}
520 The unary \code{-} (minus) operator yields the negation of its
521 numeric argument.
522 \index{negation}
523 \index{minus}
525 The unary \code{+} (plus) operator yields its numeric argument
526 unchanged.
527 \index{plus}
529 The unary \code{~} (invert) operator yields the bit-wise inversion
530 of its plain or long integer argument. The bit-wise inversion of
531 \code{x} is defined as \code{-(x+1)}. It only applies to integral
532 numbers.
533 \index{inversion}
535 In all three cases, if the argument does not have the proper type,
536 a \exception{TypeError} exception is raised.
537 \exindex{TypeError}
539 \section{Binary arithmetic operations\label{binary}}
540 \indexiii{binary}{arithmetic}{operation}
542 The binary arithmetic operations have the conventional priority
543 levels. Note that some of these operations also apply to certain
544 non-numeric types. Apart from the power operator, there are only two
545 levels, one for multiplicative operators and one for additive
546 operators:
548 \begin{verbatim}
549 m_expr: u_expr | m_expr "*" u_expr
550 | m_expr "/" u_expr | m_expr "%" u_expr
551 a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
552 \end{verbatim}
554 The \code{*} (multiplication) operator yields the product of its
555 arguments. The arguments must either both be numbers, or one argument
556 must be a plain integer and the other must be a sequence. In the
557 former case, the numbers are converted to a common type and then
558 multiplied together. In the latter case, sequence repetition is
559 performed; a negative repetition factor yields an empty sequence.
560 \index{multiplication}
562 The \code{/} (division) operator yields the quotient of its
563 arguments. The numeric arguments are first converted to a common
564 type. Plain or long integer division yields an integer of the same
565 type; the result is that of mathematical division with the `floor'
566 function applied to the result. Division by zero raises the
567 \exception{ZeroDivisionError} exception.
568 \exindex{ZeroDivisionError}
569 \index{division}
571 The \code{\%} (modulo) operator yields the remainder from the
572 division of the first argument by the second. The numeric arguments
573 are first converted to a common type. A zero right argument raises
574 the \exception{ZeroDivisionError} exception. The arguments may be floating
575 point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
576 \code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
577 yields a result with the same sign as its second operand (or zero);
578 the absolute value of the result is strictly smaller than the second
579 operand.
580 \index{modulo}
582 The integer division and modulo operators are connected by the
583 following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
584 modulo are also connected with the built-in function \function{divmod()}:
585 \code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
586 floating point and complex numbers; there similar identities hold
587 approximately where \code{x/y} is replaced by \code{floor(x/y)}) or
588 \code{floor(x/y) - 1} (for floats),\footnote{
589 If x is very close to an exact integer multiple of y, it's
590 possible for \code{floor(x/y)} to be one larger than
591 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
592 the latter result, in order to preserve that \code{divmod(x,y)[0]
593 * y + x \%{} y} be very close to \code{x}.
594 } or \code{floor((x/y).real)} (for
595 complex).
597 The \code{+} (addition) operator yields the sum of its arguments.
598 The arguments must either both be numbers or both sequences of the
599 same type. In the former case, the numbers are converted to a common
600 type and then added together. In the latter case, the sequences are
601 concatenated.
602 \index{addition}
604 The \code{-} (subtraction) operator yields the difference of its
605 arguments. The numeric arguments are first converted to a common
606 type.
607 \index{subtraction}
609 \section{Shifting operations\label{shifting}}
610 \indexii{shifting}{operation}
612 The shifting operations have lower priority than the arithmetic
613 operations:
615 \begin{verbatim}
616 shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
617 \end{verbatim}
619 These operators accept plain or long integers as arguments. The
620 arguments are converted to a common type. They shift the first
621 argument to the left or right by the number of bits given by the
622 second argument.
624 A right shift by \var{n} bits is defined as division by
625 \code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
626 multiplication with \code{pow(2,\var{n})}; for plain integers there is
627 no overflow check so in that case the operation drops bits and flips
628 the sign if the result is not less than \code{pow(2,31)} in absolute
629 value. Negative shift counts raise a \exception{ValueError}
630 exception.
631 \exindex{ValueError}
633 \section{Binary bit-wise operations\label{bitwise}}
634 \indexiii{binary}{bit-wise}{operation}
636 Each of the three bitwise operations has a different priority level:
638 \begin{verbatim}
639 and_expr: shift_expr | and_expr "&" shift_expr
640 xor_expr: and_expr | xor_expr "^" and_expr
641 or_expr: xor_expr | or_expr "|" xor_expr
642 \end{verbatim}
644 The \code{\&} operator yields the bitwise AND of its arguments, which
645 must be plain or long integers. The arguments are converted to a
646 common type.
647 \indexii{bit-wise}{and}
649 The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
650 arguments, which must be plain or long integers. The arguments are
651 converted to a common type.
652 \indexii{bit-wise}{xor}
653 \indexii{exclusive}{or}
655 The \code{|} operator yields the bitwise (inclusive) OR of its
656 arguments, which must be plain or long integers. The arguments are
657 converted to a common type.
658 \indexii{bit-wise}{or}
659 \indexii{inclusive}{or}
661 \section{Comparisons\label{comparisons}}
662 \index{comparison}
664 Contrary to \C, all comparison operations in Python have the same
665 priority, which is lower than that of any arithmetic, shifting or
666 bitwise operation. Also contrary to \C, expressions like
667 \code{a < b < c} have the interpretation that is conventional in
668 mathematics:
669 \indexii{C}{language}
671 \begin{verbatim}
672 comparison: or_expr (comp_operator or_expr)*
673 comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
674 \end{verbatim}
676 Comparisons yield integer values: \code{1} for true, \code{0} for false.
678 Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
679 equivalent to \code{x < y and y <= z}, except that \code{y} is
680 evaluated only once (but in both cases \code{z} is not evaluated at all
681 when \code{x < y} is found to be false).
682 \indexii{chaining}{comparisons}
684 Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
685 expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
686 operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
687 to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
688 \var{y opy z}, except that each expression is evaluated at most once.
690 Note that \var{a opa b opb c} doesn't imply any kind of comparison
691 between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
692 perfectly legal (though perhaps not pretty).
694 The forms \code{<>} and \code{!=} are equivalent; for consistency with
695 C, \code{!=} is preferred; where \code{!=} is mentioned below
696 \code{<>} is also acceptable. At some point in the (far) future,
697 \code{<>} may become obsolete.
699 The operators \texttt{"<", ">", "==", ">=", "<="}, and \texttt{"!="} compare
700 the values of two objects. The objects needn't have the same type.
701 If both are numbers, they are coverted to a common type. Otherwise,
702 objects of different types \emph{always} compare unequal, and are
703 ordered consistently but arbitrarily.
705 (This unusual definition of comparison was used to simplify the
706 definition of operations like sorting and the \keyword{in} and
707 \keyword{not in} operators. In the future, the comparison rules for
708 objects of different types are likely to change.)
710 Comparison of objects of the same type depends on the type:
712 \begin{itemize}
714 \item
715 Numbers are compared arithmetically.
717 \item
718 Strings are compared lexicographically using the numeric equivalents
719 (the result of the built-in function \function{ord()}) of their
720 characters.
722 \item
723 Tuples and lists are compared lexicographically using comparison of
724 corresponding items.
726 \item
727 Mappings (dictionaries) are compared through lexicographic
728 comparison of their sorted (key, value) lists.\footnote{
729 This is expensive since it requires sorting the keys first,
730 but it is about the only sensible definition. An earlier version of
731 Python compared dictionaries by identity only, but this caused
732 surprises because people expected to be able to test a dictionary for
733 emptiness by comparing it to \code{\{\}}.}
735 \item
736 Most other types compare unequal unless they are the same object;
737 the choice whether one object is considered smaller or larger than
738 another one is made arbitrarily but consistently within one
739 execution of a program.
741 \end{itemize}
743 The operators \keyword{in} and \keyword{not in} test for sequence
744 membership: if \var{y} is a sequence, \code{\var{x} in \var{y}} is
745 true if and only if there exists an index \var{i} such that
746 \code{\var{x} = \var{y}[\var{i}]}.
747 \code{\var{x} not in \var{y}} yields the inverse truth value. The
748 exception \exception{TypeError} is raised when \var{y} is not a sequence,
749 or when \var{y} is a string and \var{x} is not a string of length
750 one.\footnote{The latter restriction is sometimes a nuisance.}
751 \opindex{in}
752 \opindex{not in}
753 \indexii{membership}{test}
754 \obindex{sequence}
756 The operators \keyword{is} and \keyword{is not} test for object identity:
757 \code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
758 are the same object. \code{\var{x} is not \var{y}} yields the inverse
759 truth value.
760 \opindex{is}
761 \opindex{is not}
762 \indexii{identity}{test}
764 \section{Boolean operations\label{Booleans}}
765 \indexii{Boolean}{operation}
767 Boolean operations have the lowest priority of all Python operations:
769 \begin{verbatim}
770 expression: or_test | lambda_form
771 or_test: and_test | or_test "or" and_test
772 and_test: not_test | and_test "and" not_test
773 not_test: comparison | "not" not_test
774 lambda_form: "lambda" [parameter_list]: expression
775 \end{verbatim}
777 In the context of Boolean operations, and also when expressions are
778 used by control flow statements, the following values are interpreted
779 as false: \code{None}, numeric zero of all types, empty sequences
780 (strings, tuples and lists), and empty mappings (dictionaries). All
781 other values are interpreted as true.
783 The operator \keyword{not} yields \code{1} if its argument is false,
784 \code{0} otherwise.
785 \opindex{not}
787 The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
788 \var{x} is false, its value is returned; otherwise, \var{y} is
789 evaluated and the resulting value is returned.
790 \opindex{and}
792 The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
793 \var{x} is true, its value is returned; otherwise, \var{y} is
794 evaluated and the resulting value is returned.
795 \opindex{or}
797 (Note that neither \keyword{and} nor \keyword{or} restrict the value
798 and type they return to \code{0} and \code{1}, but rather return the
799 last evaluated argument.
800 This is sometimes useful, e.g., if \code{s} is a string that should be
801 replaced by a default value if it is empty, the expression
802 \code{s or 'foo'} yields the desired value. Because \keyword{not} has to
803 invent a value anyway, it does not bother to return a value of the
804 same type as its argument, so e.g., \code{not 'foo'} yields \code{0},
805 not \code{''}.)
807 Lambda forms (lambda expressions) have the same syntactic position as
808 expressions. They are a shorthand to create anonymous functions; the
809 expression \code{lambda \var{arguments}: \var{expression}}
810 yields a function object that behaves virtually identical to one
811 defined with
813 \begin{verbatim}
814 def name(arguments):
815 return expression
816 \end{verbatim}
818 See section \ref{function} for the syntax of parameter lists. Note
819 that functions created with lambda forms cannot contain statements.
820 \label{lambda}
821 \indexii{lambda}{expression}
822 \indexii{lambda}{form}
823 \indexii{anonmymous}{function}
825 \strong{Programmer's note:} a lambda form defined inside a function
826 has no access to names defined in the function's namespace. This is
827 because Python has only two scopes: local and global. A common
828 work-around is to use default argument values to pass selected
829 variables into the lambda's namespace, e.g.:
831 \begin{verbatim}
832 def make_incrementor(increment):
833 return lambda x, n=increment: x+n
834 \end{verbatim}
836 \section{Expression lists\label{exprlists}}
837 \indexii{expression}{list}
839 \begin{verbatim}
840 expression_list: expression ("," expression)* [","]
841 \end{verbatim}
843 An expression (expression) list containing at least one comma yields a
844 tuple. The length of the tuple is the number of expressions in the
845 list. The expressions are evaluated from left to right.
846 \obindex{tuple}
848 The trailing comma is required only to create a single tuple (a.k.a. a
849 \emph{singleton}); it is optional in all other cases. A single
850 expression (expression) without a trailing comma doesn't create a
851 tuple, but rather yields the value of that expression (expression).
852 (To create an empty tuple, use an empty pair of parentheses:
853 \code{()}.)
854 \indexii{trailing}{comma}
857 \section{Summary\label{summary}}
859 The following table summarizes the operator
860 precedences\indexii{operator}{precedence} in Python, from lowest
861 precedence (least binding) to highest precedence (most binding).
862 Operators in the same box have the same precedence. Unless the syntax
863 is explicitly given, operators are binary. Operators in the same box
864 group left to right (except for comparisons, which chain from left to
865 right --- see above).
867 \begin{tableii}{c|l}{textrm}{Operator}{Description}
868 \lineii{\keyword{lambda}} {Lambda expression}
869 \hline
870 \lineii{\keyword{or}} {Boolean OR}
871 \hline
872 \lineii{\keyword{and}} {Boolean AND}
873 \hline
874 \lineii{\keyword{not} \var{x}} {Boolean NOT}
875 \hline
876 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
877 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
878 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
879 \code{<>}, \code{!=}, \code{==}}
880 {Comparisons}
881 \hline
882 \lineii{\code{|}} {Bitwise OR}
883 \hline
884 \lineii{\code{\^}} {Bitwise XOR}
885 \hline
886 \lineii{\code{\&}} {Bitwise AND}
887 \hline
888 \lineii{\code{<<}, \code{>>}} {Shifts}
889 \hline
890 \lineii{\code{+}, \code{-}}{Addition and subtraction}
891 \hline
892 \lineii{\code{*}, \code{/}, \code{\%}}
893 {Multiplication, division, remainder}
894 \hline
895 \lineii{\code{**}} {Exponentiation}
896 \hline
897 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
898 \lineii{\code{\~\var{x}}} {Bitwise not}
899 \hline
900 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
901 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
902 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
903 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
904 \hline
905 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
906 \lineii{\code{[\var{expressions}\ldots]}} {List display}
907 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
908 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
909 \end{tableii}