blob: 9590ee422159889a75367b3847c58e1014ccf037 [file] [log] [blame]
Fred Drake020f8c01998-07-28 19:32:59 +00001\chapter{Expressions\label{expressions}}
Fred Drakef6669171998-05-06 19:52:49 +00002\index{expression}
Fred Drakef6669171998-05-06 19:52:49 +00003
Guido van Rossum3a0ad601998-07-23 21:57:42 +00004This chapter explains the meaning of the elements of expressions in
5Python.
Fred Drakef6669171998-05-06 19:52:49 +00006
Guido van Rossum3a0ad601998-07-23 21:57:42 +00007\strong{Syntax Notes:} In this and the following chapters, extended
8BNF\index{BNF} notation will be used to describe syntax, not lexical
9analysis. When (one alternative of) a syntax rule has the form
Fred Drakef6669171998-05-06 19:52:49 +000010
11\begin{verbatim}
12name: othername
13\end{verbatim}
14
Fred Drake5c07d9b1998-05-14 19:37:06 +000015and no semantics are given, the semantics of this form of \code{name}
16are the same as for \code{othername}.
Fred Drakef6669171998-05-06 19:52:49 +000017\index{syntax}
18
Fred Drake020f8c01998-07-28 19:32:59 +000019\section{Arithmetic conversions\label{conversions}}
Fred Drakef6669171998-05-06 19:52:49 +000020\indexii{arithmetic}{conversion}
21
22When a description of an arithmetic operator below uses the phrase
Guido van Rossum3a0ad601998-07-23 21:57:42 +000023``the numeric arguments are converted to a common type,'' the
24arguments are coerced using the coercion rules listed at the end of
25chapter 3. If both arguments are standard numeric types, the
26following coercions are applied:
Fred Drakef6669171998-05-06 19:52:49 +000027
28\begin{itemize}
Guido van Rossum3a0ad601998-07-23 21:57:42 +000029\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,
Fred Drakef6669171998-05-06 19:52:49 +000032 the other is converted to floating point;
Guido van Rossum3a0ad601998-07-23 21:57:42 +000033\item otherwise, if either argument is a long integer,
Fred Drakef6669171998-05-06 19:52:49 +000034 the other is converted to long integer;
35\item otherwise, both must be plain integers and no conversion
36 is necessary.
37\end{itemize}
38
Guido van Rossum7c0240f1998-07-24 15:36:43 +000039Some additional rules apply for certain operators (e.g., a string left
Guido van Rossum3a0ad601998-07-23 21:57:42 +000040argument to the `\%' operator). Extensions can define their own
41coercions.
Fred Drake020f8c01998-07-28 19:32:59 +000042
43
44\section{Atoms\label{atoms}}
Fred Drakef6669171998-05-06 19:52:49 +000045\index{atom}
46
Guido van Rossum3a0ad601998-07-23 21:57:42 +000047Atoms are the most basic elements of expressions. The simplest atoms
48are identifiers or literals. Forms enclosed in
Fred Drakef6669171998-05-06 19:52:49 +000049reverse quotes or in parentheses, brackets or braces are also
50categorized syntactically as atoms. The syntax for atoms is:
51
52\begin{verbatim}
53atom: identifier | literal | enclosure
54enclosure: parenth_form|list_display|dict_display|string_conversion
55\end{verbatim}
56
Fred Drake020f8c01998-07-28 19:32:59 +000057\subsection{Identifiers (Names)\label{atom-identifiers}}
Fred Drakef6669171998-05-06 19:52:49 +000058\index{name}
59\index{identifier}
60
61An identifier occurring as an atom is a reference to a local, global
62or built-in name binding. If a name is assigned to anywhere in a code
63block (even in unreachable code), and is not mentioned in a
Fred Drake5c07d9b1998-05-14 19:37:06 +000064\keyword{global} statement in that code block, then it refers to a local
Fred Drakef6669171998-05-06 19:52:49 +000065name throughout that code block. When it is not assigned to anywhere
66in the block, or when it is assigned to but also explicitly listed in
Fred Drake5c07d9b1998-05-14 19:37:06 +000067a \keyword{global} statement, it refers to a global name if one exists,
Fred Drakeac79e952001-03-06 07:32:11 +000068else to a built-in name (and this binding may dynamically
69change).\footnote{The Python interpreter provides a useful set of
70 predefined built-in functions. It is not recommended to reuse
71 (hide) these names with self defined objects. See the
72 \citetitle[../lib/built-in-funcs.html]{Python Library Reference} for
73 the descriptions of built-in functions and methods.}
Fred Drakef6669171998-05-06 19:52:49 +000074\indexii{name}{binding}
75\index{code block}
76\stindex{global}
77\indexii{built-in}{name}
78\indexii{global}{name}
79
80When the name is bound to an object, evaluation of the atom yields
81that object. When a name is not bound, an attempt to evaluate it
Fred Drake5c07d9b1998-05-14 19:37:06 +000082raises a \exception{NameError} exception.
Fred Drakef6669171998-05-06 19:52:49 +000083\exindex{NameError}
84
Guido van Rossum3a0ad601998-07-23 21:57:42 +000085\strong{Private name mangling:}%
86\indexii{name}{mangling}%
87\indexii{private}{names}%
88when an identifier that textually occurs in a class definition begins
89with two or more underscore characters and does not end in two or more
Fred Drakeea81edf1998-11-25 17:51:15 +000090underscores, it is considered a \dfn{private name} of that class.
Guido van Rossum3a0ad601998-07-23 21:57:42 +000091Private names are transformed to a longer form before code is
92generated for them. The transformation inserts the class name in
93front of the name, with leading underscores removed, and a single
94underscore inserted in front of the class name. For example, the
95identifier \code{__spam} occurring in a class named \code{Ham} will be
96transformed to \code{_Ham__spam}. This transformation is independent
97of the syntactical context in which the identifier is used. If the
98transformed name is extremely long (longer than 255 characters),
99implementation defined truncation may happen. If the class name
100consists only of underscores, no transformation is done.
101
Fred Drake020f8c01998-07-28 19:32:59 +0000102\subsection{Literals\label{atom-literals}}
Fred Drakef6669171998-05-06 19:52:49 +0000103\index{literal}
104
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000105Python supports string literals and various numeric literals:
Fred Drakef6669171998-05-06 19:52:49 +0000106
107\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000108literal: stringliteral | integer | longinteger | floatnumber | imagnumber
Fred Drakef6669171998-05-06 19:52:49 +0000109\end{verbatim}
110
111Evaluation of a literal yields an object of the given type (string,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000112integer, long integer, floating point number, complex number) with the
113given value. The value may be approximated in the case of floating
114point and imaginary (complex) literals. See section \ref{literals}
115for details.
Fred Drakef6669171998-05-06 19:52:49 +0000116
117All literals correspond to immutable data types, and hence the
118object's identity is less important than its value. Multiple
119evaluations of literals with the same value (either the same
120occurrence in the program text or a different occurrence) may obtain
121the same object or a different object with the same value.
122\indexiii{immutable}{data}{type}
Fred Drakee15956b2000-04-03 04:51:13 +0000123\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000124
Fred Drake020f8c01998-07-28 19:32:59 +0000125\subsection{Parenthesized forms\label{parenthesized}}
Fred Drakef6669171998-05-06 19:52:49 +0000126\index{parenthesized form}
127
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000128A parenthesized form is an optional expression list enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000129parentheses:
130
131\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000132parenth_form: "(" [expression_list] ")"
Fred Drakef6669171998-05-06 19:52:49 +0000133\end{verbatim}
134
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000135A parenthesized expression list yields whatever that expression list
136yields: if the list contains at least one comma, it yields a tuple;
137otherwise, it yields the single expression that makes up the
138expression list.
Fred Drakef6669171998-05-06 19:52:49 +0000139
140An empty pair of parentheses yields an empty tuple object. Since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000141tuples are immutable, the rules for literals apply (i.e., two
142occurrences of the empty tuple may or may not yield the same object).
Fred Drakef6669171998-05-06 19:52:49 +0000143\indexii{empty}{tuple}
144
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000145Note that tuples are not formed by the parentheses, but rather by use
Fred Drakef6669171998-05-06 19:52:49 +0000146of the comma operator. The exception is the empty tuple, for which
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000147parentheses \emph{are} required --- allowing unparenthesized ``nothing''
Fred Drakef6669171998-05-06 19:52:49 +0000148in expressions would cause ambiguities and allow common typos to
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000149pass uncaught.
Fred Drakef6669171998-05-06 19:52:49 +0000150\index{comma}
151\indexii{tuple}{display}
152
Fred Drake020f8c01998-07-28 19:32:59 +0000153\subsection{List displays\label{lists}}
Fred Drakef6669171998-05-06 19:52:49 +0000154\indexii{list}{display}
Skip Montanarob6559392000-09-11 16:31:55 +0000155\indexii{list}{comprehensions}
Fred Drakef6669171998-05-06 19:52:49 +0000156
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000157A list display is a possibly empty series of expressions enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000158square brackets:
159
160\begin{verbatim}
Fred Drakea1e214a2000-08-15 17:54:49 +0000161list_display: "[" [listmaker] "]"
Skip Montanaro46dfa5f2000-08-22 02:43:07 +0000162listmaker: expression ( list_for | ( "," expression)* [","] )
Skip Montanaro803d6e52000-08-12 18:09:51 +0000163list_iter: list_for | list_if
164list_for: "for" expression_list "in" testlist [list_iter]
165list_if: "if" test [list_iter]
Fred Drakef6669171998-05-06 19:52:49 +0000166\end{verbatim}
167
Skip Montanaro803d6e52000-08-12 18:09:51 +0000168A list display yields a new list object. Its contents are specified
169by providing either a list of expressions or a list comprehension.
Skip Montanarob6559392000-09-11 16:31:55 +0000170\indexii{list}{comprehensions}
Skip Montanaro803d6e52000-08-12 18:09:51 +0000171When a comma-separated list of expressions is supplied, its elements are
172evaluated from left to right and placed into the list object in that
173order. When a list comprehension is supplied, it consists of a
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000174single expression followed by at least one \keyword{for} clause and zero or
175more \keyword{for} or \keyword{if} clauses. In this
Skip Montanaro803d6e52000-08-12 18:09:51 +0000176case, the elements of the new list are those that would be produced
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000177by considering each of the \keyword{for} or \keyword{if} clauses a block,
178nesting from
Skip Montanaro803d6e52000-08-12 18:09:51 +0000179left to right, and evaluating the expression to produce a list element
180each time the innermost block is reached.
Fred Drakef6669171998-05-06 19:52:49 +0000181\obindex{list}
Fred Drakef6669171998-05-06 19:52:49 +0000182\indexii{empty}{list}
183
Fred Drake020f8c01998-07-28 19:32:59 +0000184\subsection{Dictionary displays\label{dict}}
Fred Drakef6669171998-05-06 19:52:49 +0000185\indexii{dictionary}{display}
186
187A dictionary display is a possibly empty series of key/datum pairs
188enclosed in curly braces:
189\index{key}
190\index{datum}
191\index{key/datum pair}
192
193\begin{verbatim}
194dict_display: "{" [key_datum_list] "}"
195key_datum_list: key_datum ("," key_datum)* [","]
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000196key_datum: expression ":" expression
Fred Drakef6669171998-05-06 19:52:49 +0000197\end{verbatim}
198
199A dictionary display yields a new dictionary object.
200\obindex{dictionary}
201
202The key/datum pairs are evaluated from left to right to define the
203entries of the dictionary: each key object is used as a key into the
204dictionary to store the corresponding datum.
205
206Restrictions on the types of the key values are listed earlier in
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000207section \ref{types}. (To summarize,the key type should be hashable,
208which excludes all mutable objects.) Clashes between duplicate keys
209are not detected; the last datum (textually rightmost in the display)
210stored for a given key value prevails.
Fred Drakee15956b2000-04-03 04:51:13 +0000211\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000212
Fred Drake020f8c01998-07-28 19:32:59 +0000213\subsection{String conversions\label{string-conversions}}
Fred Drakef6669171998-05-06 19:52:49 +0000214\indexii{string}{conversion}
215\indexii{reverse}{quotes}
216\indexii{backward}{quotes}
217\index{back-quotes}
218
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000219A string conversion is an expression list enclosed in reverse (a.k.a.
Fred Drakef6669171998-05-06 19:52:49 +0000220backward) quotes:
221
222\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000223string_conversion: "`" expression_list "`"
Fred Drakef6669171998-05-06 19:52:49 +0000224\end{verbatim}
225
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000226A string conversion evaluates the contained expression list and
Fred Drakef6669171998-05-06 19:52:49 +0000227converts the resulting object into a string according to rules
228specific to its type.
229
Fred Drake5c07d9b1998-05-14 19:37:06 +0000230If the object is a string, a number, \code{None}, or a tuple, list or
Fred Drakef6669171998-05-06 19:52:49 +0000231dictionary containing only objects whose type is one of these, the
232resulting string is a valid Python expression which can be passed to
Fred Drake5c07d9b1998-05-14 19:37:06 +0000233the built-in function \function{eval()} to yield an expression with the
Fred Drakef6669171998-05-06 19:52:49 +0000234same value (or an approximation, if floating point numbers are
235involved).
236
237(In particular, converting a string adds quotes around it and converts
238``funny'' characters to escape sequences that are safe to print.)
239
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000240It is illegal to attempt to convert recursive objects (e.g., lists or
Fred Drakef6669171998-05-06 19:52:49 +0000241dictionaries that contain a reference to themselves, directly or
242indirectly.)
243\obindex{recursive}
244
Fred Drake5c07d9b1998-05-14 19:37:06 +0000245The built-in function \function{repr()} performs exactly the same
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000246conversion in its argument as enclosing it in parentheses and reverse
247quotes does. The built-in function \function{str()} performs a
248similar but more user-friendly conversion.
Fred Drakef6669171998-05-06 19:52:49 +0000249\bifuncindex{repr}
250\bifuncindex{str}
251
Fred Drake020f8c01998-07-28 19:32:59 +0000252\section{Primaries\label{primaries}}
Fred Drakef6669171998-05-06 19:52:49 +0000253\index{primary}
254
255Primaries represent the most tightly bound operations of the language.
256Their syntax is:
257
258\begin{verbatim}
259primary: atom | attributeref | subscription | slicing | call
260\end{verbatim}
261
Fred Drake020f8c01998-07-28 19:32:59 +0000262\subsection{Attribute references\label{attribute-references}}
Fred Drakef6669171998-05-06 19:52:49 +0000263\indexii{attribute}{reference}
264
265An attribute reference is a primary followed by a period and a name:
266
267\begin{verbatim}
268attributeref: primary "." identifier
269\end{verbatim}
270
271The primary must evaluate to an object of a type that supports
Fred Drake34bafcc2001-01-14 02:57:14 +0000272attribute references, e.g., a module, list, or an instance. This
273object is then asked to produce the attribute whose name is the
274identifier. If this attribute is not available, the exception
Fred Drake5c07d9b1998-05-14 19:37:06 +0000275\exception{AttributeError}\exindex{AttributeError} is raised.
276Otherwise, the type and value of the object produced is determined by
277the object. Multiple evaluations of the same attribute reference may
278yield different objects.
Fred Drakef6669171998-05-06 19:52:49 +0000279\obindex{module}
280\obindex{list}
281
Fred Drake020f8c01998-07-28 19:32:59 +0000282\subsection{Subscriptions\label{subscriptions}}
Fred Drakef6669171998-05-06 19:52:49 +0000283\index{subscription}
284
285A subscription selects an item of a sequence (string, tuple or list)
286or mapping (dictionary) object:
287\obindex{sequence}
288\obindex{mapping}
289\obindex{string}
290\obindex{tuple}
291\obindex{list}
292\obindex{dictionary}
293\indexii{sequence}{item}
294
295\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000296subscription: primary "[" expression_list "]"
Fred Drakef6669171998-05-06 19:52:49 +0000297\end{verbatim}
298
299The primary must evaluate to an object of a sequence or mapping type.
300
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000301If the primary is a mapping, the expression list must evaluate to an
302object whose value is one of the keys of the mapping, and the
303subscription selects the value in the mapping that corresponds to that
304key. (The expression list is a tuple except if it has exactly one
305item.)
Fred Drakef6669171998-05-06 19:52:49 +0000306
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000307If the primary is a sequence, the expression (list) must evaluate to a
308plain integer. If this value is negative, the length of the sequence
309is added to it (so that, e.g., \code{x[-1]} selects the last item of
310\code{x}.) The resulting value must be a nonnegative integer less
311than the number of items in the sequence, and the subscription selects
312the item whose index is that value (counting from zero).
Fred Drakef6669171998-05-06 19:52:49 +0000313
314A string's items are characters. A character is not a separate data
315type but a string of exactly one character.
316\index{character}
317\indexii{string}{item}
318
Fred Drake020f8c01998-07-28 19:32:59 +0000319\subsection{Slicings\label{slicings}}
Fred Drakef6669171998-05-06 19:52:49 +0000320\index{slicing}
321\index{slice}
322
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000323A slicing selects a range of items in a sequence object (e.g., a
324string, tuple or list). Slicings may be used as expressions or as
325targets in assignment or del statements. The syntax for a slicing:
Fred Drakef6669171998-05-06 19:52:49 +0000326\obindex{sequence}
327\obindex{string}
328\obindex{tuple}
329\obindex{list}
330
331\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000332slicing: simple_slicing | extended_slicing
333simple_slicing: primary "[" short_slice "]"
334extended_slicing: primary "[" slice_list "]"
335slice_list: slice_item ("," slice_item)* [","]
336slice_item: expression | proper_slice | ellipsis
337proper_slice: short_slice | long_slice
338short_slice: [lower_bound] ":" [upper_bound]
339long_slice: short_slice ":" [stride]
340lower_bound: expression
341upper_bound: expression
342stride: expression
343ellipsis: "..."
Fred Drakef6669171998-05-06 19:52:49 +0000344\end{verbatim}
345
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000346There is ambiguity in the formal syntax here: anything that looks like
347an expression list also looks like a slice list, so any subscription
348can be interpreted as a slicing. Rather than further complicating the
349syntax, this is disambiguated by defining that in this case the
350interpretation as a subscription takes priority over the
351interpretation as a slicing (this is the case if the slice list
352contains no proper slice nor ellipses). Similarly, when the slice
353list has exactly one short slice and no trailing comma, the
354interpretation as a simple slicing takes priority over that as an
355extended slicing.\indexii{extended}{slicing}
356
357The semantics for a simple slicing are as follows. The primary must
358evaluate to a sequence object. The lower and upper bound expressions,
359if present, must evaluate to plain integers; defaults are zero and the
Fred Drakee15956b2000-04-03 04:51:13 +0000360\code{sys.maxint}, respectively. If either bound is negative, the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000361sequence's length is added to it. The slicing now selects all items
362with index \var{k} such that
Fred Drakef6669171998-05-06 19:52:49 +0000363\code{\var{i} <= \var{k} < \var{j}} where \var{i}
364and \var{j} are the specified lower and upper bounds. This may be an
365empty sequence. It is not an error if \var{i} or \var{j} lie outside the
366range of valid indexes (such items don't exist so they aren't
367selected).
368
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000369The semantics for an extended slicing are as follows. The primary
370must evaluate to a mapping object, and it is indexed with a key that
371is constructed from the slice list, as follows. If the slice list
372contains at least one comma, the key is a tuple containing the
373conversion of the slice items; otherwise, the conversion of the lone
374slice item is the key. The conversion of a slice item that is an
375expression is that expression. The conversion of an ellipsis slice
376item is the built-in \code{Ellipsis} object. The conversion of a
377proper slice is a slice object (see section \ref{types}) whose
Fred Drakeea81edf1998-11-25 17:51:15 +0000378\member{start}, \member{stop} and \member{step} attributes are the
379values of the expressions given as lower bound, upper bound and
380stride, respectively, substituting \code{None} for missing
381expressions.
Fred Drake99cd5731999-02-12 20:40:09 +0000382\withsubitem{(slice object attribute)}{\ttindex{start}
383 \ttindex{stop}\ttindex{step}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000384
Fred Drake020f8c01998-07-28 19:32:59 +0000385\subsection{Calls\label{calls}}
Fred Drakef6669171998-05-06 19:52:49 +0000386\index{call}
387
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000388A call calls a callable object (e.g., a function) with a possibly empty
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000389series of arguments:
Fred Drakef6669171998-05-06 19:52:49 +0000390\obindex{callable}
391
392\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000393call: primary "(" [argument_list [","]] ")"
394argument_list: positional_arguments ["," keyword_arguments]
395 | keyword_arguments
396positional_arguments: expression ("," expression)*
397keyword_arguments: keyword_item ("," keyword_item)*
398keyword_item: identifier "=" expression
Fred Drakef6669171998-05-06 19:52:49 +0000399\end{verbatim}
400
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000401A trailing comma may be present after an argument list but does not
402affect the semantics.
403
Fred Drakef6669171998-05-06 19:52:49 +0000404The primary must evaluate to a callable object (user-defined
405functions, built-in functions, methods of built-in objects, class
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000406objects, methods of class instances, and certain class instances
407themselves are callable; extensions may define additional callable
408object types). All argument expressions are evaluated before the call
409is attempted. Please refer to section \ref{function} for the syntax
410of formal parameter lists.
411
412If keyword arguments are present, they are first converted to
413positional arguments, as follows. First, a list of unfilled slots is
414created for the formal parameters. If there are N positional
415arguments, they are placed in the first N slots. Next, for each
416keyword argument, the identifier is used to determine the
417corresponding slot (if the identifier is the same as the first formal
418parameter name, the first slot is used, and so on). If the slot is
419already filled, a \exception{TypeError} exception is raised.
420Otherwise, the value of the argument is placed in the slot, filling it
421(even if the expression is \code{None}, it fills the slot). When all
422arguments have been processed, the slots that are still unfilled are
423filled with the corresponding default value from the function
424definition. (Default values are calculated, once, when the function
425is defined; thus, a mutable object such as a list or dictionary used
426as default value will be shared by all calls that don't specify an
427argument value for the corresponding slot; this should usually be
428avoided.) If there are any unfilled slots for which no default value
429is specified, a \exception{TypeError} exception is raised. Otherwise,
430the list of filled slots is used as the argument list for the call.
431
432If there are more positional arguments than there are formal parameter
433slots, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000434parameter using the syntax \samp{*identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000435case, that formal parameter receives a tuple containing the excess
436positional arguments (or an empty tuple if there were no excess
437positional arguments).
438
439If any keyword argument does not correspond to a formal parameter
440name, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000441parameter using the syntax \samp{**identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000442case, that formal parameter receives a dictionary containing the
443excess keyword arguments (using the keywords as keys and the argument
444values as corresponding values), or a (new) empty dictionary if there
445were no excess keyword arguments.
446
Fred Drakeea81edf1998-11-25 17:51:15 +0000447Formal parameters using the syntax \samp{*identifier} or
448\samp{**identifier} cannot be used as positional argument slots or
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000449as keyword argument names. Formal parameters using the syntax
Fred Drakeea81edf1998-11-25 17:51:15 +0000450\samp{(sublist)} cannot be used as keyword argument names; the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000451outermost sublist corresponds to a single unnamed argument slot, and
452the argument value is assigned to the sublist using the usual tuple
453assignment rules after all other parameter processing is done.
Fred Drakef6669171998-05-06 19:52:49 +0000454
Fred Drake5c07d9b1998-05-14 19:37:06 +0000455A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000456raises an exception. How this value is computed depends on the type
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000457of the callable object.
458
459If it is---
Fred Drakef6669171998-05-06 19:52:49 +0000460
461\begin{description}
462
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000463\item[a user-defined function:] The code block for the function is
Fred Drakef6669171998-05-06 19:52:49 +0000464executed, passing it the argument list. The first thing the code
465block will do is bind the formal parameters to the arguments; this is
466described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000467\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000468function call.
469\indexii{function}{call}
470\indexiii{user-defined}{function}{call}
471\obindex{user-defined function}
472\obindex{function}
473
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000474\item[a built-in function or method:] The result is up to the
Fred Drake3d83fc32000-07-31 20:08:23 +0000475interpreter; see the \citetitle[../lib/built-in-funcs.html]{Python
476Library Reference} for the descriptions of built-in functions and
477methods.
Fred Drakef6669171998-05-06 19:52:49 +0000478\indexii{function}{call}
479\indexii{built-in function}{call}
480\indexii{method}{call}
481\indexii{built-in method}{call}
482\obindex{built-in method}
483\obindex{built-in function}
484\obindex{method}
485\obindex{function}
486
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000487\item[a class object:] A new instance of that class is returned.
Fred Drakef6669171998-05-06 19:52:49 +0000488\obindex{class}
489\indexii{class object}{call}
490
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000491\item[a class instance method:] The corresponding user-defined
Fred Drakef6669171998-05-06 19:52:49 +0000492function is called, with an argument list that is one longer than the
493argument list of the call: the instance becomes the first argument.
494\obindex{class instance}
495\obindex{instance}
Fred Drakef6669171998-05-06 19:52:49 +0000496\indexii{class instance}{call}
497
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000498\item[a class instance:] The class must define a \method{__call__()}
499method; the effect is then the same as if that method was called.
500\indexii{instance}{call}
Fred Drakeea81edf1998-11-25 17:51:15 +0000501\withsubitem{(object method)}{\ttindex{__call__()}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000502
Fred Drakef6669171998-05-06 19:52:49 +0000503\end{description}
504
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000505
Fred Drake020f8c01998-07-28 19:32:59 +0000506\section{The power operator\label{power}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000507
508The power operator binds more tightly than unary operators on its
509left; it binds less tightly than unary operators on its right. The
510syntax is:
511
512\begin{verbatim}
513power: primary ["**" u_expr]
514\end{verbatim}
515
516Thus, in an unparenthesized sequence of power and unary operators, the
517operators are evaluated from right to left (this does not constrain
518the evaluation order for the operands).
519
520The power operator has the same semantics as the built-in
521\function{pow()} function, when called with two arguments: it yields
522its left argument raised to the power of its right argument. The
523numeric arguments are first converted to a common type. The result
524type is that of the arguments after coercion; if the result is not
525expressible in that type (as in raising an integer to a negative
526power, or a negative floating point number to a broken power), a
527\exception{TypeError} exception is raised.
528
529
Fred Drakee15956b2000-04-03 04:51:13 +0000530\section{Unary arithmetic operations \label{unary}}
Fred Drakef6669171998-05-06 19:52:49 +0000531\indexiii{unary}{arithmetic}{operation}
532\indexiii{unary}{bit-wise}{operation}
533
534All unary arithmetic (and bit-wise) operations have the same priority:
535
536\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000537u_expr: power | "-" u_expr | "+" u_expr | "~" u_expr
Fred Drakef6669171998-05-06 19:52:49 +0000538\end{verbatim}
539
Fred Drake5c07d9b1998-05-14 19:37:06 +0000540The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000541numeric argument.
542\index{negation}
543\index{minus}
544
Fred Drake5c07d9b1998-05-14 19:37:06 +0000545The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000546unchanged.
547\index{plus}
548
Fred Drakee15956b2000-04-03 04:51:13 +0000549The unary \code{\~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000550of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000551\code{x} is defined as \code{-(x+1)}. It only applies to integral
552numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000553\index{inversion}
554
555In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000556a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000557\exindex{TypeError}
558
Fred Drake020f8c01998-07-28 19:32:59 +0000559\section{Binary arithmetic operations\label{binary}}
Fred Drakef6669171998-05-06 19:52:49 +0000560\indexiii{binary}{arithmetic}{operation}
561
562The binary arithmetic operations have the conventional priority
563levels. Note that some of these operations also apply to certain
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000564non-numeric types. Apart from the power operator, there are only two
565levels, one for multiplicative operators and one for additive
Fred Drakef6669171998-05-06 19:52:49 +0000566operators:
567
568\begin{verbatim}
569m_expr: u_expr | m_expr "*" u_expr
570 | m_expr "/" u_expr | m_expr "%" u_expr
571a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
572\end{verbatim}
573
Fred Drake5c07d9b1998-05-14 19:37:06 +0000574The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000575arguments. The arguments must either both be numbers, or one argument
Fred Drakec3b18d72000-12-07 04:54:02 +0000576must be an integer (plain or long) and the other must be a sequence.
577In the former case, the numbers are converted to a common type and
578then multiplied together. In the latter case, sequence repetition is
Fred Drakef6669171998-05-06 19:52:49 +0000579performed; a negative repetition factor yields an empty sequence.
580\index{multiplication}
581
Fred Drake5c07d9b1998-05-14 19:37:06 +0000582The \code{/} (division) operator yields the quotient of its
Fred Drakef6669171998-05-06 19:52:49 +0000583arguments. The numeric arguments are first converted to a common
584type. Plain or long integer division yields an integer of the same
585type; the result is that of mathematical division with the `floor'
586function applied to the result. Division by zero raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000587\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000588\exindex{ZeroDivisionError}
589\index{division}
590
Fred Drake5c07d9b1998-05-14 19:37:06 +0000591The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000592division of the first argument by the second. The numeric arguments
593are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000594the \exception{ZeroDivisionError} exception. The arguments may be floating
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000595point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000596\code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
597yields a result with the same sign as its second operand (or zero);
598the absolute value of the result is strictly smaller than the second
599operand.
Fred Drakef6669171998-05-06 19:52:49 +0000600\index{modulo}
601
602The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000603following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
604modulo are also connected with the built-in function \function{divmod()}:
605\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Fred Drake1ea7c751999-05-06 14:46:35 +0000606floating point and complex numbers; there similar identities hold
607approximately where \code{x/y} is replaced by \code{floor(x/y)}) or
608\code{floor(x/y) - 1} (for floats),\footnote{
609 If x is very close to an exact integer multiple of y, it's
610 possible for \code{floor(x/y)} to be one larger than
611 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
612 the latter result, in order to preserve that \code{divmod(x,y)[0]
613 * y + x \%{} y} be very close to \code{x}.
614} or \code{floor((x/y).real)} (for
615complex).
Fred Drakef6669171998-05-06 19:52:49 +0000616
Fred Drake5c07d9b1998-05-14 19:37:06 +0000617The \code{+} (addition) operator yields the sum of its arguments.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000618The arguments must either both be numbers or both sequences of the
Fred Drakef6669171998-05-06 19:52:49 +0000619same type. In the former case, the numbers are converted to a common
620type and then added together. In the latter case, the sequences are
621concatenated.
622\index{addition}
623
Fred Drake5c07d9b1998-05-14 19:37:06 +0000624The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000625arguments. The numeric arguments are first converted to a common
626type.
627\index{subtraction}
628
Fred Drake020f8c01998-07-28 19:32:59 +0000629\section{Shifting operations\label{shifting}}
Fred Drakef6669171998-05-06 19:52:49 +0000630\indexii{shifting}{operation}
631
632The shifting operations have lower priority than the arithmetic
633operations:
634
635\begin{verbatim}
636shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
637\end{verbatim}
638
639These operators accept plain or long integers as arguments. The
640arguments are converted to a common type. They shift the first
641argument to the left or right by the number of bits given by the
642second argument.
643
644A right shift by \var{n} bits is defined as division by
645\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
646multiplication with \code{pow(2,\var{n})}; for plain integers there is
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000647no overflow check so in that case the operation drops bits and flips
648the sign if the result is not less than \code{pow(2,31)} in absolute
649value. Negative shift counts raise a \exception{ValueError}
650exception.
Fred Drakef6669171998-05-06 19:52:49 +0000651\exindex{ValueError}
652
Fred Drake020f8c01998-07-28 19:32:59 +0000653\section{Binary bit-wise operations\label{bitwise}}
Fred Drakef6669171998-05-06 19:52:49 +0000654\indexiii{binary}{bit-wise}{operation}
655
656Each of the three bitwise operations has a different priority level:
657
658\begin{verbatim}
659and_expr: shift_expr | and_expr "&" shift_expr
660xor_expr: and_expr | xor_expr "^" and_expr
661or_expr: xor_expr | or_expr "|" xor_expr
662\end{verbatim}
663
Fred Drake5c07d9b1998-05-14 19:37:06 +0000664The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000665must be plain or long integers. The arguments are converted to a
666common type.
667\indexii{bit-wise}{and}
668
Fred Drake5c07d9b1998-05-14 19:37:06 +0000669The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000670arguments, which must be plain or long integers. The arguments are
671converted to a common type.
672\indexii{bit-wise}{xor}
673\indexii{exclusive}{or}
674
Fred Drake5c07d9b1998-05-14 19:37:06 +0000675The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000676arguments, which must be plain or long integers. The arguments are
677converted to a common type.
678\indexii{bit-wise}{or}
679\indexii{inclusive}{or}
680
Fred Drake020f8c01998-07-28 19:32:59 +0000681\section{Comparisons\label{comparisons}}
Fred Drakef6669171998-05-06 19:52:49 +0000682\index{comparison}
683
Fred Drake1156f622000-09-19 18:10:05 +0000684Unlike C, all comparison operations in Python have the same priority,
685which is lower than that of any arithmetic, shifting or bitwise
686operation. Also unlike C, expressions like \code{a < b < c} have the
687interpretation that is conventional in mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000688\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000689
690\begin{verbatim}
691comparison: or_expr (comp_operator or_expr)*
692comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
693\end{verbatim}
694
Fred Drake5c07d9b1998-05-14 19:37:06 +0000695Comparisons yield integer values: \code{1} for true, \code{0} for false.
Fred Drakef6669171998-05-06 19:52:49 +0000696
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000697Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
Fred Drakef6669171998-05-06 19:52:49 +0000698equivalent to \code{x < y and y <= z}, except that \code{y} is
699evaluated only once (but in both cases \code{z} is not evaluated at all
700when \code{x < y} is found to be false).
701\indexii{chaining}{comparisons}
702
703Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
704expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
705operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000706to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
Fred Drakef6669171998-05-06 19:52:49 +0000707\var{y opy z}, except that each expression is evaluated at most once.
708
709Note that \var{a opa b opb c} doesn't imply any kind of comparison
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000710between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
Fred Drakef6669171998-05-06 19:52:49 +0000711perfectly legal (though perhaps not pretty).
712
Fred Drake5c07d9b1998-05-14 19:37:06 +0000713The forms \code{<>} and \code{!=} are equivalent; for consistency with
714C, \code{!=} is preferred; where \code{!=} is mentioned below
Fred Drake1156f622000-09-19 18:10:05 +0000715\code{<>} is also accepted. The \code{<>} spelling is considered
716obsolescent.
Fred Drakef6669171998-05-06 19:52:49 +0000717
Fred Drake1156f622000-09-19 18:10:05 +0000718The operators \code{<}, \code{>}, \code{==}, \code{>=}, \code{<=}, and
719\code{!=} compare
720the values of two objects. The objects need not have the same type.
Fred Drakef6669171998-05-06 19:52:49 +0000721If both are numbers, they are coverted to a common type. Otherwise,
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000722objects of different types \emph{always} compare unequal, and are
Fred Drakef6669171998-05-06 19:52:49 +0000723ordered consistently but arbitrarily.
724
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000725(This unusual definition of comparison was used to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000726definition of operations like sorting and the \keyword{in} and
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000727\keyword{not in} operators. In the future, the comparison rules for
728objects of different types are likely to change.)
Fred Drakef6669171998-05-06 19:52:49 +0000729
730Comparison of objects of the same type depends on the type:
731
732\begin{itemize}
733
734\item
735Numbers are compared arithmetically.
736
737\item
738Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +0000739(the result of the built-in function \function{ord()}) of their
Fred Drake1156f622000-09-19 18:10:05 +0000740characters. Unicode and 8-bit strings are fully interoperable in this
741behavior.
Fred Drakef6669171998-05-06 19:52:49 +0000742
743\item
744Tuples and lists are compared lexicographically using comparison of
745corresponding items.
746
747\item
748Mappings (dictionaries) are compared through lexicographic
Fred Drakeb55ce1e1999-04-05 21:32:52 +0000749comparison of their sorted (key, value) lists.\footnote{
750This is expensive since it requires sorting the keys first,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000751but it is about the only sensible definition. An earlier version of
752Python compared dictionaries by identity only, but this caused
753surprises because people expected to be able to test a dictionary for
754emptiness by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +0000755
756\item
757Most other types compare unequal unless they are the same object;
758the choice whether one object is considered smaller or larger than
759another one is made arbitrarily but consistently within one
760execution of a program.
761
762\end{itemize}
763
Fred Drake7399b9e2000-07-11 19:43:47 +0000764The operators \keyword{in} and \keyword{not in} test for set
Fred Drakeac79e952001-03-06 07:32:11 +0000765membership. \code{\var{x} in \var{s}} evaluates to true if \var{x}
766is a member of the set \var{s}, and false otherwise. \code{\var{x}
767not in \var{s}} returns the negation of \code{\var{x} in \var{s}}.
768The set membership test has traditionally been bound to sequences; an
769object is a member of a set if the set is a sequence and contains an
770element equal to that object. However, it is possible for an object
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +0000771to support membership tests without being a sequence. In particular,
772dictionaries support memership testing as a nicer way of spelling
773\code{\var{key} in \var{dict}}; other mapping types may follow suit.
Fred Drake7399b9e2000-07-11 19:43:47 +0000774
Fred Drake34bafcc2001-01-14 02:57:14 +0000775For the list and tuple types, \code{\var{x} in \var{y}} is true if and
Fred Drakeac79e952001-03-06 07:32:11 +0000776only if there exists an index \var{i} such that
Fred Drake34bafcc2001-01-14 02:57:14 +0000777\code{\var{x} == \var{y}[\var{i}]} is true.
Fred Drake7399b9e2000-07-11 19:43:47 +0000778
Fred Drake1156f622000-09-19 18:10:05 +0000779For the Unicode and string types, \code{\var{x} in \var{y}} is true if
780and only if there exists an index \var{i} such that \code{\var{x} ==
781\var{y}[\var{i}]} is true. If \code{\var{x}} is not a string or
782Unicode object of length \code{1}, a \exception{TypeError} exception
783is raised.
Fred Drake7399b9e2000-07-11 19:43:47 +0000784
785For user-defined classes which define the \method{__contains__()} method,
786\code{\var{x} in \var{y}} is true if and only if
787\code{\var{y}.__contains__(\var{x})} is true.
788
789For user-defined classes which do not define \method{__contains__()} and
Fred Drake1156f622000-09-19 18:10:05 +0000790do define \method{__getitem__()}, \code{\var{x} in \var{y}} is true if
791and only if there is a non-negative integer index \var{i} such that
Fred Drake7399b9e2000-07-11 19:43:47 +0000792\code{\var{x} == \var{y}[\var{i}]}, and all lower integer indices
793do not raise \exception{IndexError} exception. (If any other exception
794is raised, it is as if \keyword{in} raised that exception).
795
796The operator \keyword{not in} is defined to have the inverse true value
797of \keyword{in}.
Fred Drakef6669171998-05-06 19:52:49 +0000798\opindex{in}
799\opindex{not in}
800\indexii{membership}{test}
801\obindex{sequence}
802
Fred Drake5c07d9b1998-05-14 19:37:06 +0000803The operators \keyword{is} and \keyword{is not} test for object identity:
804\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
805are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +0000806truth value.
807\opindex{is}
808\opindex{is not}
809\indexii{identity}{test}
810
Fred Drake020f8c01998-07-28 19:32:59 +0000811\section{Boolean operations\label{Booleans}}
Fred Drakef6669171998-05-06 19:52:49 +0000812\indexii{Boolean}{operation}
813
814Boolean operations have the lowest priority of all Python operations:
815
816\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000817expression: or_test | lambda_form
Fred Drakef6669171998-05-06 19:52:49 +0000818or_test: and_test | or_test "or" and_test
819and_test: not_test | and_test "and" not_test
820not_test: comparison | "not" not_test
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000821lambda_form: "lambda" [parameter_list]: expression
Fred Drakef6669171998-05-06 19:52:49 +0000822\end{verbatim}
823
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000824In the context of Boolean operations, and also when expressions are
Fred Drakef6669171998-05-06 19:52:49 +0000825used by control flow statements, the following values are interpreted
Fred Drake5c07d9b1998-05-14 19:37:06 +0000826as false: \code{None}, numeric zero of all types, empty sequences
Fred Drakef6669171998-05-06 19:52:49 +0000827(strings, tuples and lists), and empty mappings (dictionaries). All
828other values are interpreted as true.
829
Fred Drake5c07d9b1998-05-14 19:37:06 +0000830The operator \keyword{not} yields \code{1} if its argument is false,
831\code{0} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +0000832\opindex{not}
833
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000834The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000835\var{x} is false, its value is returned; otherwise, \var{y} is
836evaluated and the resulting value is returned.
837\opindex{and}
838
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000839The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000840\var{x} is true, its value is returned; otherwise, \var{y} is
841evaluated and the resulting value is returned.
842\opindex{or}
843
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000844(Note that neither \keyword{and} nor \keyword{or} restrict the value
Fred Drake5c07d9b1998-05-14 19:37:06 +0000845and type they return to \code{0} and \code{1}, but rather return the
846last evaluated argument.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000847This is sometimes useful, e.g., if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +0000848replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +0000849\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +0000850invent a value anyway, it does not bother to return a value of the
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000851same type as its argument, so e.g., \code{not 'foo'} yields \code{0},
Fred Drake5c07d9b1998-05-14 19:37:06 +0000852not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +0000853
854Lambda forms (lambda expressions) have the same syntactic position as
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000855expressions. They are a shorthand to create anonymous functions; the
856expression \code{lambda \var{arguments}: \var{expression}}
Fred Drakef6669171998-05-06 19:52:49 +0000857yields a function object that behaves virtually identical to one
858defined with
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000859
860\begin{verbatim}
861def name(arguments):
862 return expression
863\end{verbatim}
864
865See section \ref{function} for the syntax of parameter lists. Note
866that functions created with lambda forms cannot contain statements.
Fred Drakef6669171998-05-06 19:52:49 +0000867\label{lambda}
868\indexii{lambda}{expression}
869\indexii{lambda}{form}
870\indexii{anonmymous}{function}
871
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000872\strong{Programmer's note:} a lambda form defined inside a function
873has no access to names defined in the function's namespace. This is
874because Python has only two scopes: local and global. A common
875work-around is to use default argument values to pass selected
876variables into the lambda's namespace, e.g.:
Fred Drakef6669171998-05-06 19:52:49 +0000877
878\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000879def make_incrementor(increment):
880 return lambda x, n=increment: x+n
Fred Drakef6669171998-05-06 19:52:49 +0000881\end{verbatim}
882
Fred Drake020f8c01998-07-28 19:32:59 +0000883\section{Expression lists\label{exprlists}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000884\indexii{expression}{list}
Fred Drakef6669171998-05-06 19:52:49 +0000885
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000886\begin{verbatim}
887expression_list: expression ("," expression)* [","]
888\end{verbatim}
Fred Drakef6669171998-05-06 19:52:49 +0000889
Fred Drakec009d192000-04-25 21:09:10 +0000890An expression list containing at least one comma yields a
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000891tuple. The length of the tuple is the number of expressions in the
892list. The expressions are evaluated from left to right.
Fred Drakef6669171998-05-06 19:52:49 +0000893\obindex{tuple}
894
895The trailing comma is required only to create a single tuple (a.k.a. a
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000896\emph{singleton}); it is optional in all other cases. A single
Fred Drakec009d192000-04-25 21:09:10 +0000897expression without a trailing comma doesn't create a
898tuple, but rather yields the value of that expression.
Fred Drakef6669171998-05-06 19:52:49 +0000899(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000900\code{()}.)
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000901\indexii{trailing}{comma}
Fred Drakef6669171998-05-06 19:52:49 +0000902
Fred Draked09120b1999-04-29 16:43:42 +0000903
Fred Drake020f8c01998-07-28 19:32:59 +0000904\section{Summary\label{summary}}
Fred Drakef6669171998-05-06 19:52:49 +0000905
Fred Draked09120b1999-04-29 16:43:42 +0000906The following table summarizes the operator
907precedences\indexii{operator}{precedence} in Python, from lowest
908precedence (least binding) to highest precedence (most binding).
909Operators in the same box have the same precedence. Unless the syntax
910is explicitly given, operators are binary. Operators in the same box
911group left to right (except for comparisons, which chain from left to
Fred Drake2a222002000-12-11 22:39:24 +0000912right --- see above, and exponentiation, which groups from right to
913left).
Fred Drakef6669171998-05-06 19:52:49 +0000914
Fred Draked09120b1999-04-29 16:43:42 +0000915\begin{tableii}{c|l}{textrm}{Operator}{Description}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000916 \lineii{\keyword{lambda}} {Lambda expression}
917 \hline
918 \lineii{\keyword{or}} {Boolean OR}
919 \hline
920 \lineii{\keyword{and}} {Boolean AND}
921 \hline
922 \lineii{\keyword{not} \var{x}} {Boolean NOT}
923 \hline
924 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
925 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
926 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
Fred Drake9beee801998-10-21 00:44:49 +0000927 \code{<>}, \code{!=}, \code{==}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000928 {Comparisons}
929 \hline
930 \lineii{\code{|}} {Bitwise OR}
931 \hline
932 \lineii{\code{\^}} {Bitwise XOR}
933 \hline
934 \lineii{\code{\&}} {Bitwise AND}
935 \hline
Fred Drake24e7a292001-04-12 12:37:03 +0000936 \lineii{\code{<}\code{<}, \code{>}\code{>}} {Shifts}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000937 \hline
938 \lineii{\code{+}, \code{-}}{Addition and subtraction}
939 \hline
Fred Drake9beee801998-10-21 00:44:49 +0000940 \lineii{\code{*}, \code{/}, \code{\%}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000941 {Multiplication, division, remainder}
942 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000943 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
944 \lineii{\code{\~\var{x}}} {Bitwise not}
945 \hline
Fred Drakeb8ac0092001-05-09 16:51:49 +0000946 \lineii{\code{**}} {Exponentiation}
947 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000948 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
949 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
950 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
951 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
Fred Draked09120b1999-04-29 16:43:42 +0000952 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000953 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
954 \lineii{\code{[\var{expressions}\ldots]}} {List display}
955 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
956 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
957\end{tableii}