blob: 55725d197a45442595c370a2b3e471bd569b4eae [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 Drakef6669171998-05-06 19:52:49 +000068else 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}
74
75When the name is bound to an object, evaluation of the atom yields
76that object. When a name is not bound, an attempt to evaluate it
Fred Drake5c07d9b1998-05-14 19:37:06 +000077raises a \exception{NameError} exception.
Fred Drakef6669171998-05-06 19:52:49 +000078\exindex{NameError}
79
Guido van Rossum3a0ad601998-07-23 21:57:42 +000080\strong{Private name mangling:}%
81\indexii{name}{mangling}%
82\indexii{private}{names}%
83when an identifier that textually occurs in a class definition begins
84with two or more underscore characters and does not end in two or more
Fred Drakeea81edf1998-11-25 17:51:15 +000085underscores, it is considered a \dfn{private name} of that class.
Guido van Rossum3a0ad601998-07-23 21:57:42 +000086Private names are transformed to a longer form before code is
87generated for them. The transformation inserts the class name in
88front of the name, with leading underscores removed, and a single
89underscore inserted in front of the class name. For example, the
90identifier \code{__spam} occurring in a class named \code{Ham} will be
91transformed to \code{_Ham__spam}. This transformation is independent
92of the syntactical context in which the identifier is used. If the
93transformed name is extremely long (longer than 255 characters),
94implementation defined truncation may happen. If the class name
95consists only of underscores, no transformation is done.
96
Fred Drake020f8c01998-07-28 19:32:59 +000097\subsection{Literals\label{atom-literals}}
Fred Drakef6669171998-05-06 19:52:49 +000098\index{literal}
99
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000100Python supports string literals and various numeric literals:
Fred Drakef6669171998-05-06 19:52:49 +0000101
102\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000103literal: stringliteral | integer | longinteger | floatnumber | imagnumber
Fred Drakef6669171998-05-06 19:52:49 +0000104\end{verbatim}
105
106Evaluation of a literal yields an object of the given type (string,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000107integer, long integer, floating point number, complex number) with the
108given value. The value may be approximated in the case of floating
109point and imaginary (complex) literals. See section \ref{literals}
110for details.
Fred Drakef6669171998-05-06 19:52:49 +0000111
112All literals correspond to immutable data types, and hence the
113object's identity is less important than its value. Multiple
114evaluations of literals with the same value (either the same
115occurrence in the program text or a different occurrence) may obtain
116the same object or a different object with the same value.
117\indexiii{immutable}{data}{type}
Fred Drakee15956b2000-04-03 04:51:13 +0000118\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000119
Fred Drake020f8c01998-07-28 19:32:59 +0000120\subsection{Parenthesized forms\label{parenthesized}}
Fred Drakef6669171998-05-06 19:52:49 +0000121\index{parenthesized form}
122
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000123A parenthesized form is an optional expression list enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000124parentheses:
125
126\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000127parenth_form: "(" [expression_list] ")"
Fred Drakef6669171998-05-06 19:52:49 +0000128\end{verbatim}
129
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000130A parenthesized expression list yields whatever that expression list
131yields: if the list contains at least one comma, it yields a tuple;
132otherwise, it yields the single expression that makes up the
133expression list.
Fred Drakef6669171998-05-06 19:52:49 +0000134
135An empty pair of parentheses yields an empty tuple object. Since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000136tuples are immutable, the rules for literals apply (i.e., two
137occurrences of the empty tuple may or may not yield the same object).
Fred Drakef6669171998-05-06 19:52:49 +0000138\indexii{empty}{tuple}
139
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000140Note that tuples are not formed by the parentheses, but rather by use
Fred Drakef6669171998-05-06 19:52:49 +0000141of the comma operator. The exception is the empty tuple, for which
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000142parentheses \emph{are} required --- allowing unparenthesized ``nothing''
Fred Drakef6669171998-05-06 19:52:49 +0000143in expressions would cause ambiguities and allow common typos to
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000144pass uncaught.
Fred Drakef6669171998-05-06 19:52:49 +0000145\index{comma}
146\indexii{tuple}{display}
147
Fred Drake020f8c01998-07-28 19:32:59 +0000148\subsection{List displays\label{lists}}
Fred Drakef6669171998-05-06 19:52:49 +0000149\indexii{list}{display}
150
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000151A list display is a possibly empty series of expressions enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000152square brackets:
153
154\begin{verbatim}
Fred Drakea1e214a2000-08-15 17:54:49 +0000155list_display: "[" [listmaker] "]"
Skip Montanaro46dfa5f2000-08-22 02:43:07 +0000156listmaker: expression ( list_for | ( "," expression)* [","] )
Skip Montanaro803d6e52000-08-12 18:09:51 +0000157list_iter: list_for | list_if
158list_for: "for" expression_list "in" testlist [list_iter]
159list_if: "if" test [list_iter]
Fred Drakef6669171998-05-06 19:52:49 +0000160\end{verbatim}
161
Skip Montanaro803d6e52000-08-12 18:09:51 +0000162A list display yields a new list object. Its contents are specified
163by providing either a list of expressions or a list comprehension.
164When a comma-separated list of expressions is supplied, its elements are
165evaluated from left to right and placed into the list object in that
166order. When a list comprehension is supplied, it consists of a
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000167single expression followed by at least one \keyword{for} clause and zero or
168more \keyword{for} or \keyword{if} clauses. In this
Skip Montanaro803d6e52000-08-12 18:09:51 +0000169case, the elements of the new list are those that would be produced
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000170by considering each of the \keyword{for} or \keyword{if} clauses a block,
171nesting from
Skip Montanaro803d6e52000-08-12 18:09:51 +0000172left to right, and evaluating the expression to produce a list element
173each time the innermost block is reached.
Fred Drakef6669171998-05-06 19:52:49 +0000174\obindex{list}
Fred Drakef6669171998-05-06 19:52:49 +0000175\indexii{empty}{list}
176
Fred Drake020f8c01998-07-28 19:32:59 +0000177\subsection{Dictionary displays\label{dict}}
Fred Drakef6669171998-05-06 19:52:49 +0000178\indexii{dictionary}{display}
179
180A dictionary display is a possibly empty series of key/datum pairs
181enclosed in curly braces:
182\index{key}
183\index{datum}
184\index{key/datum pair}
185
186\begin{verbatim}
187dict_display: "{" [key_datum_list] "}"
188key_datum_list: key_datum ("," key_datum)* [","]
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000189key_datum: expression ":" expression
Fred Drakef6669171998-05-06 19:52:49 +0000190\end{verbatim}
191
192A dictionary display yields a new dictionary object.
193\obindex{dictionary}
194
195The key/datum pairs are evaluated from left to right to define the
196entries of the dictionary: each key object is used as a key into the
197dictionary to store the corresponding datum.
198
199Restrictions on the types of the key values are listed earlier in
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000200section \ref{types}. (To summarize,the key type should be hashable,
201which excludes all mutable objects.) Clashes between duplicate keys
202are not detected; the last datum (textually rightmost in the display)
203stored for a given key value prevails.
Fred Drakee15956b2000-04-03 04:51:13 +0000204\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000205
Fred Drake020f8c01998-07-28 19:32:59 +0000206\subsection{String conversions\label{string-conversions}}
Fred Drakef6669171998-05-06 19:52:49 +0000207\indexii{string}{conversion}
208\indexii{reverse}{quotes}
209\indexii{backward}{quotes}
210\index{back-quotes}
211
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000212A string conversion is an expression list enclosed in reverse (a.k.a.
Fred Drakef6669171998-05-06 19:52:49 +0000213backward) quotes:
214
215\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000216string_conversion: "`" expression_list "`"
Fred Drakef6669171998-05-06 19:52:49 +0000217\end{verbatim}
218
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000219A string conversion evaluates the contained expression list and
Fred Drakef6669171998-05-06 19:52:49 +0000220converts the resulting object into a string according to rules
221specific to its type.
222
Fred Drake5c07d9b1998-05-14 19:37:06 +0000223If the object is a string, a number, \code{None}, or a tuple, list or
Fred Drakef6669171998-05-06 19:52:49 +0000224dictionary containing only objects whose type is one of these, the
225resulting string is a valid Python expression which can be passed to
Fred Drake5c07d9b1998-05-14 19:37:06 +0000226the built-in function \function{eval()} to yield an expression with the
Fred Drakef6669171998-05-06 19:52:49 +0000227same value (or an approximation, if floating point numbers are
228involved).
229
230(In particular, converting a string adds quotes around it and converts
231``funny'' characters to escape sequences that are safe to print.)
232
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000233It is illegal to attempt to convert recursive objects (e.g., lists or
Fred Drakef6669171998-05-06 19:52:49 +0000234dictionaries that contain a reference to themselves, directly or
235indirectly.)
236\obindex{recursive}
237
Fred Drake5c07d9b1998-05-14 19:37:06 +0000238The built-in function \function{repr()} performs exactly the same
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000239conversion in its argument as enclosing it in parentheses and reverse
240quotes does. The built-in function \function{str()} performs a
241similar but more user-friendly conversion.
Fred Drakef6669171998-05-06 19:52:49 +0000242\bifuncindex{repr}
243\bifuncindex{str}
244
Fred Drake020f8c01998-07-28 19:32:59 +0000245\section{Primaries\label{primaries}}
Fred Drakef6669171998-05-06 19:52:49 +0000246\index{primary}
247
248Primaries represent the most tightly bound operations of the language.
249Their syntax is:
250
251\begin{verbatim}
252primary: atom | attributeref | subscription | slicing | call
253\end{verbatim}
254
Fred Drake020f8c01998-07-28 19:32:59 +0000255\subsection{Attribute references\label{attribute-references}}
Fred Drakef6669171998-05-06 19:52:49 +0000256\indexii{attribute}{reference}
257
258An attribute reference is a primary followed by a period and a name:
259
260\begin{verbatim}
261attributeref: primary "." identifier
262\end{verbatim}
263
264The primary must evaluate to an object of a type that supports
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000265attribute references, e.g., a module or a list. This object is then
Fred Drakef6669171998-05-06 19:52:49 +0000266asked to produce the attribute whose name is the identifier. If this
Fred Drake5c07d9b1998-05-14 19:37:06 +0000267attribute is not available, the exception
268\exception{AttributeError}\exindex{AttributeError} is raised.
269Otherwise, the type and value of the object produced is determined by
270the object. Multiple evaluations of the same attribute reference may
271yield different objects.
Fred Drakef6669171998-05-06 19:52:49 +0000272\obindex{module}
273\obindex{list}
274
Fred Drake020f8c01998-07-28 19:32:59 +0000275\subsection{Subscriptions\label{subscriptions}}
Fred Drakef6669171998-05-06 19:52:49 +0000276\index{subscription}
277
278A subscription selects an item of a sequence (string, tuple or list)
279or mapping (dictionary) object:
280\obindex{sequence}
281\obindex{mapping}
282\obindex{string}
283\obindex{tuple}
284\obindex{list}
285\obindex{dictionary}
286\indexii{sequence}{item}
287
288\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000289subscription: primary "[" expression_list "]"
Fred Drakef6669171998-05-06 19:52:49 +0000290\end{verbatim}
291
292The primary must evaluate to an object of a sequence or mapping type.
293
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000294If the primary is a mapping, the expression list must evaluate to an
295object whose value is one of the keys of the mapping, and the
296subscription selects the value in the mapping that corresponds to that
297key. (The expression list is a tuple except if it has exactly one
298item.)
Fred Drakef6669171998-05-06 19:52:49 +0000299
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000300If the primary is a sequence, the expression (list) must evaluate to a
301plain integer. If this value is negative, the length of the sequence
302is added to it (so that, e.g., \code{x[-1]} selects the last item of
303\code{x}.) The resulting value must be a nonnegative integer less
304than the number of items in the sequence, and the subscription selects
305the item whose index is that value (counting from zero).
Fred Drakef6669171998-05-06 19:52:49 +0000306
307A string's items are characters. A character is not a separate data
308type but a string of exactly one character.
309\index{character}
310\indexii{string}{item}
311
Fred Drake020f8c01998-07-28 19:32:59 +0000312\subsection{Slicings\label{slicings}}
Fred Drakef6669171998-05-06 19:52:49 +0000313\index{slicing}
314\index{slice}
315
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000316A slicing selects a range of items in a sequence object (e.g., a
317string, tuple or list). Slicings may be used as expressions or as
318targets in assignment or del statements. The syntax for a slicing:
Fred Drakef6669171998-05-06 19:52:49 +0000319\obindex{sequence}
320\obindex{string}
321\obindex{tuple}
322\obindex{list}
323
324\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000325slicing: simple_slicing | extended_slicing
326simple_slicing: primary "[" short_slice "]"
327extended_slicing: primary "[" slice_list "]"
328slice_list: slice_item ("," slice_item)* [","]
329slice_item: expression | proper_slice | ellipsis
330proper_slice: short_slice | long_slice
331short_slice: [lower_bound] ":" [upper_bound]
332long_slice: short_slice ":" [stride]
333lower_bound: expression
334upper_bound: expression
335stride: expression
336ellipsis: "..."
Fred Drakef6669171998-05-06 19:52:49 +0000337\end{verbatim}
338
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000339There is ambiguity in the formal syntax here: anything that looks like
340an expression list also looks like a slice list, so any subscription
341can be interpreted as a slicing. Rather than further complicating the
342syntax, this is disambiguated by defining that in this case the
343interpretation as a subscription takes priority over the
344interpretation as a slicing (this is the case if the slice list
345contains no proper slice nor ellipses). Similarly, when the slice
346list has exactly one short slice and no trailing comma, the
347interpretation as a simple slicing takes priority over that as an
348extended slicing.\indexii{extended}{slicing}
349
350The semantics for a simple slicing are as follows. The primary must
351evaluate to a sequence object. The lower and upper bound expressions,
352if present, must evaluate to plain integers; defaults are zero and the
Fred Drakee15956b2000-04-03 04:51:13 +0000353\code{sys.maxint}, respectively. If either bound is negative, the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000354sequence's length is added to it. The slicing now selects all items
355with index \var{k} such that
Fred Drakef6669171998-05-06 19:52:49 +0000356\code{\var{i} <= \var{k} < \var{j}} where \var{i}
357and \var{j} are the specified lower and upper bounds. This may be an
358empty sequence. It is not an error if \var{i} or \var{j} lie outside the
359range of valid indexes (such items don't exist so they aren't
360selected).
361
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000362The semantics for an extended slicing are as follows. The primary
363must evaluate to a mapping object, and it is indexed with a key that
364is constructed from the slice list, as follows. If the slice list
365contains at least one comma, the key is a tuple containing the
366conversion of the slice items; otherwise, the conversion of the lone
367slice item is the key. The conversion of a slice item that is an
368expression is that expression. The conversion of an ellipsis slice
369item is the built-in \code{Ellipsis} object. The conversion of a
370proper slice is a slice object (see section \ref{types}) whose
Fred Drakeea81edf1998-11-25 17:51:15 +0000371\member{start}, \member{stop} and \member{step} attributes are the
372values of the expressions given as lower bound, upper bound and
373stride, respectively, substituting \code{None} for missing
374expressions.
Fred Drake99cd5731999-02-12 20:40:09 +0000375\withsubitem{(slice object attribute)}{\ttindex{start}
376 \ttindex{stop}\ttindex{step}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000377
Fred Drake020f8c01998-07-28 19:32:59 +0000378\subsection{Calls\label{calls}}
Fred Drakef6669171998-05-06 19:52:49 +0000379\index{call}
380
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000381A call calls a callable object (e.g., a function) with a possibly empty
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000382series of arguments:
Fred Drakef6669171998-05-06 19:52:49 +0000383\obindex{callable}
384
385\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000386call: primary "(" [argument_list [","]] ")"
387argument_list: positional_arguments ["," keyword_arguments]
388 | keyword_arguments
389positional_arguments: expression ("," expression)*
390keyword_arguments: keyword_item ("," keyword_item)*
391keyword_item: identifier "=" expression
Fred Drakef6669171998-05-06 19:52:49 +0000392\end{verbatim}
393
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000394A trailing comma may be present after an argument list but does not
395affect the semantics.
396
Fred Drakef6669171998-05-06 19:52:49 +0000397The primary must evaluate to a callable object (user-defined
398functions, built-in functions, methods of built-in objects, class
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000399objects, methods of class instances, and certain class instances
400themselves are callable; extensions may define additional callable
401object types). All argument expressions are evaluated before the call
402is attempted. Please refer to section \ref{function} for the syntax
403of formal parameter lists.
404
405If keyword arguments are present, they are first converted to
406positional arguments, as follows. First, a list of unfilled slots is
407created for the formal parameters. If there are N positional
408arguments, they are placed in the first N slots. Next, for each
409keyword argument, the identifier is used to determine the
410corresponding slot (if the identifier is the same as the first formal
411parameter name, the first slot is used, and so on). If the slot is
412already filled, a \exception{TypeError} exception is raised.
413Otherwise, the value of the argument is placed in the slot, filling it
414(even if the expression is \code{None}, it fills the slot). When all
415arguments have been processed, the slots that are still unfilled are
416filled with the corresponding default value from the function
417definition. (Default values are calculated, once, when the function
418is defined; thus, a mutable object such as a list or dictionary used
419as default value will be shared by all calls that don't specify an
420argument value for the corresponding slot; this should usually be
421avoided.) If there are any unfilled slots for which no default value
422is specified, a \exception{TypeError} exception is raised. Otherwise,
423the list of filled slots is used as the argument list for the call.
424
425If there are more positional arguments than there are formal parameter
426slots, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000427parameter using the syntax \samp{*identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000428case, that formal parameter receives a tuple containing the excess
429positional arguments (or an empty tuple if there were no excess
430positional arguments).
431
432If any keyword argument does not correspond to a formal parameter
433name, 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 dictionary containing the
436excess keyword arguments (using the keywords as keys and the argument
437values as corresponding values), or a (new) empty dictionary if there
438were no excess keyword arguments.
439
Fred Drakeea81edf1998-11-25 17:51:15 +0000440Formal parameters using the syntax \samp{*identifier} or
441\samp{**identifier} cannot be used as positional argument slots or
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000442as keyword argument names. Formal parameters using the syntax
Fred Drakeea81edf1998-11-25 17:51:15 +0000443\samp{(sublist)} cannot be used as keyword argument names; the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000444outermost sublist corresponds to a single unnamed argument slot, and
445the argument value is assigned to the sublist using the usual tuple
446assignment rules after all other parameter processing is done.
Fred Drakef6669171998-05-06 19:52:49 +0000447
Fred Drake5c07d9b1998-05-14 19:37:06 +0000448A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000449raises an exception. How this value is computed depends on the type
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000450of the callable object.
451
452If it is---
Fred Drakef6669171998-05-06 19:52:49 +0000453
454\begin{description}
455
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000456\item[a user-defined function:] The code block for the function is
Fred Drakef6669171998-05-06 19:52:49 +0000457executed, passing it the argument list. The first thing the code
458block will do is bind the formal parameters to the arguments; this is
459described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000460\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000461function call.
462\indexii{function}{call}
463\indexiii{user-defined}{function}{call}
464\obindex{user-defined function}
465\obindex{function}
466
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000467\item[a built-in function or method:] The result is up to the
Fred Drake3d83fc32000-07-31 20:08:23 +0000468interpreter; see the \citetitle[../lib/built-in-funcs.html]{Python
469Library Reference} for the descriptions of built-in functions and
470methods.
Fred Drakef6669171998-05-06 19:52:49 +0000471\indexii{function}{call}
472\indexii{built-in function}{call}
473\indexii{method}{call}
474\indexii{built-in method}{call}
475\obindex{built-in method}
476\obindex{built-in function}
477\obindex{method}
478\obindex{function}
479
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000480\item[a class object:] A new instance of that class is returned.
Fred Drakef6669171998-05-06 19:52:49 +0000481\obindex{class}
482\indexii{class object}{call}
483
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000484\item[a class instance method:] The corresponding user-defined
Fred Drakef6669171998-05-06 19:52:49 +0000485function is called, with an argument list that is one longer than the
486argument list of the call: the instance becomes the first argument.
487\obindex{class instance}
488\obindex{instance}
Fred Drakef6669171998-05-06 19:52:49 +0000489\indexii{class instance}{call}
490
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000491\item[a class instance:] The class must define a \method{__call__()}
492method; the effect is then the same as if that method was called.
493\indexii{instance}{call}
Fred Drakeea81edf1998-11-25 17:51:15 +0000494\withsubitem{(object method)}{\ttindex{__call__()}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000495
Fred Drakef6669171998-05-06 19:52:49 +0000496\end{description}
497
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000498
Fred Drake020f8c01998-07-28 19:32:59 +0000499\section{The power operator\label{power}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000500
501The power operator binds more tightly than unary operators on its
502left; it binds less tightly than unary operators on its right. The
503syntax is:
504
505\begin{verbatim}
506power: primary ["**" u_expr]
507\end{verbatim}
508
509Thus, in an unparenthesized sequence of power and unary operators, the
510operators are evaluated from right to left (this does not constrain
511the evaluation order for the operands).
512
513The power operator has the same semantics as the built-in
514\function{pow()} function, when called with two arguments: it yields
515its left argument raised to the power of its right argument. The
516numeric arguments are first converted to a common type. The result
517type is that of the arguments after coercion; if the result is not
518expressible in that type (as in raising an integer to a negative
519power, or a negative floating point number to a broken power), a
520\exception{TypeError} exception is raised.
521
522
Fred Drakee15956b2000-04-03 04:51:13 +0000523\section{Unary arithmetic operations \label{unary}}
Fred Drakef6669171998-05-06 19:52:49 +0000524\indexiii{unary}{arithmetic}{operation}
525\indexiii{unary}{bit-wise}{operation}
526
527All unary arithmetic (and bit-wise) operations have the same priority:
528
529\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000530u_expr: power | "-" u_expr | "+" u_expr | "~" u_expr
Fred Drakef6669171998-05-06 19:52:49 +0000531\end{verbatim}
532
Fred Drake5c07d9b1998-05-14 19:37:06 +0000533The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000534numeric argument.
535\index{negation}
536\index{minus}
537
Fred Drake5c07d9b1998-05-14 19:37:06 +0000538The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000539unchanged.
540\index{plus}
541
Fred Drakee15956b2000-04-03 04:51:13 +0000542The unary \code{\~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000543of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000544\code{x} is defined as \code{-(x+1)}. It only applies to integral
545numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000546\index{inversion}
547
548In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000549a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000550\exindex{TypeError}
551
Fred Drake020f8c01998-07-28 19:32:59 +0000552\section{Binary arithmetic operations\label{binary}}
Fred Drakef6669171998-05-06 19:52:49 +0000553\indexiii{binary}{arithmetic}{operation}
554
555The binary arithmetic operations have the conventional priority
556levels. Note that some of these operations also apply to certain
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000557non-numeric types. Apart from the power operator, there are only two
558levels, one for multiplicative operators and one for additive
Fred Drakef6669171998-05-06 19:52:49 +0000559operators:
560
561\begin{verbatim}
562m_expr: u_expr | m_expr "*" u_expr
563 | m_expr "/" u_expr | m_expr "%" u_expr
564a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
565\end{verbatim}
566
Fred Drake5c07d9b1998-05-14 19:37:06 +0000567The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000568arguments. The arguments must either both be numbers, or one argument
569must be a plain integer and the other must be a sequence. In the
570former case, the numbers are converted to a common type and then
571multiplied together. In the latter case, sequence repetition is
572performed; a negative repetition factor yields an empty sequence.
573\index{multiplication}
574
Fred Drake5c07d9b1998-05-14 19:37:06 +0000575The \code{/} (division) operator yields the quotient of its
Fred Drakef6669171998-05-06 19:52:49 +0000576arguments. The numeric arguments are first converted to a common
577type. Plain or long integer division yields an integer of the same
578type; the result is that of mathematical division with the `floor'
579function applied to the result. Division by zero raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000580\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000581\exindex{ZeroDivisionError}
582\index{division}
583
Fred Drake5c07d9b1998-05-14 19:37:06 +0000584The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000585division of the first argument by the second. The numeric arguments
586are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000587the \exception{ZeroDivisionError} exception. The arguments may be floating
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000588point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000589\code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
590yields a result with the same sign as its second operand (or zero);
591the absolute value of the result is strictly smaller than the second
592operand.
Fred Drakef6669171998-05-06 19:52:49 +0000593\index{modulo}
594
595The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000596following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
597modulo are also connected with the built-in function \function{divmod()}:
598\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Fred Drake1ea7c751999-05-06 14:46:35 +0000599floating point and complex numbers; there similar identities hold
600approximately where \code{x/y} is replaced by \code{floor(x/y)}) or
601\code{floor(x/y) - 1} (for floats),\footnote{
602 If x is very close to an exact integer multiple of y, it's
603 possible for \code{floor(x/y)} to be one larger than
604 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
605 the latter result, in order to preserve that \code{divmod(x,y)[0]
606 * y + x \%{} y} be very close to \code{x}.
607} or \code{floor((x/y).real)} (for
608complex).
Fred Drakef6669171998-05-06 19:52:49 +0000609
Fred Drake5c07d9b1998-05-14 19:37:06 +0000610The \code{+} (addition) operator yields the sum of its arguments.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000611The arguments must either both be numbers or both sequences of the
Fred Drakef6669171998-05-06 19:52:49 +0000612same type. In the former case, the numbers are converted to a common
613type and then added together. In the latter case, the sequences are
614concatenated.
615\index{addition}
616
Fred Drake5c07d9b1998-05-14 19:37:06 +0000617The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000618arguments. The numeric arguments are first converted to a common
619type.
620\index{subtraction}
621
Fred Drake020f8c01998-07-28 19:32:59 +0000622\section{Shifting operations\label{shifting}}
Fred Drakef6669171998-05-06 19:52:49 +0000623\indexii{shifting}{operation}
624
625The shifting operations have lower priority than the arithmetic
626operations:
627
628\begin{verbatim}
629shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
630\end{verbatim}
631
632These operators accept plain or long integers as arguments. The
633arguments are converted to a common type. They shift the first
634argument to the left or right by the number of bits given by the
635second argument.
636
637A right shift by \var{n} bits is defined as division by
638\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
639multiplication with \code{pow(2,\var{n})}; for plain integers there is
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000640no overflow check so in that case the operation drops bits and flips
641the sign if the result is not less than \code{pow(2,31)} in absolute
642value. Negative shift counts raise a \exception{ValueError}
643exception.
Fred Drakef6669171998-05-06 19:52:49 +0000644\exindex{ValueError}
645
Fred Drake020f8c01998-07-28 19:32:59 +0000646\section{Binary bit-wise operations\label{bitwise}}
Fred Drakef6669171998-05-06 19:52:49 +0000647\indexiii{binary}{bit-wise}{operation}
648
649Each of the three bitwise operations has a different priority level:
650
651\begin{verbatim}
652and_expr: shift_expr | and_expr "&" shift_expr
653xor_expr: and_expr | xor_expr "^" and_expr
654or_expr: xor_expr | or_expr "|" xor_expr
655\end{verbatim}
656
Fred Drake5c07d9b1998-05-14 19:37:06 +0000657The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000658must be plain or long integers. The arguments are converted to a
659common type.
660\indexii{bit-wise}{and}
661
Fred Drake5c07d9b1998-05-14 19:37:06 +0000662The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000663arguments, which must be plain or long integers. The arguments are
664converted to a common type.
665\indexii{bit-wise}{xor}
666\indexii{exclusive}{or}
667
Fred Drake5c07d9b1998-05-14 19:37:06 +0000668The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000669arguments, which must be plain or long integers. The arguments are
670converted to a common type.
671\indexii{bit-wise}{or}
672\indexii{inclusive}{or}
673
Fred Drake020f8c01998-07-28 19:32:59 +0000674\section{Comparisons\label{comparisons}}
Fred Drakef6669171998-05-06 19:52:49 +0000675\index{comparison}
676
Fred Drake5c07d9b1998-05-14 19:37:06 +0000677Contrary to \C, all comparison operations in Python have the same
Fred Drakef6669171998-05-06 19:52:49 +0000678priority, which is lower than that of any arithmetic, shifting or
Fred Drake5c07d9b1998-05-14 19:37:06 +0000679bitwise operation. Also contrary to \C, expressions like
680\code{a < b < c} have the interpretation that is conventional in
Fred Drakef6669171998-05-06 19:52:49 +0000681mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000682\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000683
684\begin{verbatim}
685comparison: or_expr (comp_operator or_expr)*
686comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
687\end{verbatim}
688
Fred Drake5c07d9b1998-05-14 19:37:06 +0000689Comparisons yield integer values: \code{1} for true, \code{0} for false.
Fred Drakef6669171998-05-06 19:52:49 +0000690
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000691Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
Fred Drakef6669171998-05-06 19:52:49 +0000692equivalent to \code{x < y and y <= z}, except that \code{y} is
693evaluated only once (but in both cases \code{z} is not evaluated at all
694when \code{x < y} is found to be false).
695\indexii{chaining}{comparisons}
696
697Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
698expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
699operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000700to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
Fred Drakef6669171998-05-06 19:52:49 +0000701\var{y opy z}, except that each expression is evaluated at most once.
702
703Note that \var{a opa b opb c} doesn't imply any kind of comparison
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000704between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
Fred Drakef6669171998-05-06 19:52:49 +0000705perfectly legal (though perhaps not pretty).
706
Fred Drake5c07d9b1998-05-14 19:37:06 +0000707The forms \code{<>} and \code{!=} are equivalent; for consistency with
708C, \code{!=} is preferred; where \code{!=} is mentioned below
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000709\code{<>} is also acceptable. At some point in the (far) future,
710\code{<>} may become obsolete.
Fred Drakef6669171998-05-06 19:52:49 +0000711
Fred Draked03268f1998-11-25 19:23:33 +0000712The operators \texttt{"<", ">", "==", ">=", "<="}, and \texttt{"!="} compare
Fred Drakef6669171998-05-06 19:52:49 +0000713the values of two objects. The objects needn't have the same type.
714If both are numbers, they are coverted to a common type. Otherwise,
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000715objects of different types \emph{always} compare unequal, and are
Fred Drakef6669171998-05-06 19:52:49 +0000716ordered consistently but arbitrarily.
717
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000718(This unusual definition of comparison was used to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000719definition of operations like sorting and the \keyword{in} and
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000720\keyword{not in} operators. In the future, the comparison rules for
721objects of different types are likely to change.)
Fred Drakef6669171998-05-06 19:52:49 +0000722
723Comparison of objects of the same type depends on the type:
724
725\begin{itemize}
726
727\item
728Numbers are compared arithmetically.
729
730\item
731Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +0000732(the result of the built-in function \function{ord()}) of their
733characters.
Fred Drakef6669171998-05-06 19:52:49 +0000734
735\item
736Tuples and lists are compared lexicographically using comparison of
737corresponding items.
738
739\item
740Mappings (dictionaries) are compared through lexicographic
Fred Drakeb55ce1e1999-04-05 21:32:52 +0000741comparison of their sorted (key, value) lists.\footnote{
742This is expensive since it requires sorting the keys first,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000743but it is about the only sensible definition. An earlier version of
744Python compared dictionaries by identity only, but this caused
745surprises because people expected to be able to test a dictionary for
746emptiness by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +0000747
748\item
749Most other types compare unequal unless they are the same object;
750the choice whether one object is considered smaller or larger than
751another one is made arbitrarily but consistently within one
752execution of a program.
753
754\end{itemize}
755
Fred Drake7399b9e2000-07-11 19:43:47 +0000756The operators \keyword{in} and \keyword{not in} test for set
757membership: every type can define membership in whatever way is
758appropriate. Traditionally, this interface has been tightly bound
759the sequence interface, which is related in that presence in a sequence
760can be usefully interpreted as membership in a set.
761
762For the list, tuple types, \code{\var{x} in \var{y}} is true if and only
763if there exists such an index \var{i} such that
764\code{var{x} == \var{y}[\var{i}]} is true.
765
766For the Unicode and string types, \code{\var{x} in \var{y}} is true if and only
767if there exists such an index \var{i} such that
768\code{var{x} == \var{y}[\var{i}]} is true. If \code{\var{x}} is not
769a string of length \code{1} or a unicode object of length \code{1},
770a \exception{TypeError} exception is raised.
771
772For user-defined classes which define the \method{__contains__()} method,
773\code{\var{x} in \var{y}} is true if and only if
774\code{\var{y}.__contains__(\var{x})} is true.
775
776For user-defined classes which do not define \method{__contains__()} and
777do define \var{__getitem__}, \code{\var{x} in \var{y}} is true if and only
778if there is a non-negative integer index \var{i} such that
779\code{\var{x} == \var{y}[\var{i}]}, and all lower integer indices
780do not raise \exception{IndexError} exception. (If any other exception
781is raised, it is as if \keyword{in} raised that exception).
782
783The operator \keyword{not in} is defined to have the inverse true value
784of \keyword{in}.
Fred Drakef6669171998-05-06 19:52:49 +0000785\opindex{in}
786\opindex{not in}
787\indexii{membership}{test}
788\obindex{sequence}
789
Fred Drake5c07d9b1998-05-14 19:37:06 +0000790The operators \keyword{is} and \keyword{is not} test for object identity:
791\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
792are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +0000793truth value.
794\opindex{is}
795\opindex{is not}
796\indexii{identity}{test}
797
Fred Drake020f8c01998-07-28 19:32:59 +0000798\section{Boolean operations\label{Booleans}}
Fred Drakef6669171998-05-06 19:52:49 +0000799\indexii{Boolean}{operation}
800
801Boolean operations have the lowest priority of all Python operations:
802
803\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000804expression: or_test | lambda_form
Fred Drakef6669171998-05-06 19:52:49 +0000805or_test: and_test | or_test "or" and_test
806and_test: not_test | and_test "and" not_test
807not_test: comparison | "not" not_test
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000808lambda_form: "lambda" [parameter_list]: expression
Fred Drakef6669171998-05-06 19:52:49 +0000809\end{verbatim}
810
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000811In the context of Boolean operations, and also when expressions are
Fred Drakef6669171998-05-06 19:52:49 +0000812used by control flow statements, the following values are interpreted
Fred Drake5c07d9b1998-05-14 19:37:06 +0000813as false: \code{None}, numeric zero of all types, empty sequences
Fred Drakef6669171998-05-06 19:52:49 +0000814(strings, tuples and lists), and empty mappings (dictionaries). All
815other values are interpreted as true.
816
Fred Drake5c07d9b1998-05-14 19:37:06 +0000817The operator \keyword{not} yields \code{1} if its argument is false,
818\code{0} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +0000819\opindex{not}
820
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000821The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000822\var{x} is false, its value is returned; otherwise, \var{y} is
823evaluated and the resulting value is returned.
824\opindex{and}
825
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000826The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000827\var{x} is true, its value is returned; otherwise, \var{y} is
828evaluated and the resulting value is returned.
829\opindex{or}
830
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000831(Note that neither \keyword{and} nor \keyword{or} restrict the value
Fred Drake5c07d9b1998-05-14 19:37:06 +0000832and type they return to \code{0} and \code{1}, but rather return the
833last evaluated argument.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000834This is sometimes useful, e.g., if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +0000835replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +0000836\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +0000837invent a value anyway, it does not bother to return a value of the
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000838same type as its argument, so e.g., \code{not 'foo'} yields \code{0},
Fred Drake5c07d9b1998-05-14 19:37:06 +0000839not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +0000840
841Lambda forms (lambda expressions) have the same syntactic position as
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000842expressions. They are a shorthand to create anonymous functions; the
843expression \code{lambda \var{arguments}: \var{expression}}
Fred Drakef6669171998-05-06 19:52:49 +0000844yields a function object that behaves virtually identical to one
845defined with
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000846
847\begin{verbatim}
848def name(arguments):
849 return expression
850\end{verbatim}
851
852See section \ref{function} for the syntax of parameter lists. Note
853that functions created with lambda forms cannot contain statements.
Fred Drakef6669171998-05-06 19:52:49 +0000854\label{lambda}
855\indexii{lambda}{expression}
856\indexii{lambda}{form}
857\indexii{anonmymous}{function}
858
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000859\strong{Programmer's note:} a lambda form defined inside a function
860has no access to names defined in the function's namespace. This is
861because Python has only two scopes: local and global. A common
862work-around is to use default argument values to pass selected
863variables into the lambda's namespace, e.g.:
Fred Drakef6669171998-05-06 19:52:49 +0000864
865\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000866def make_incrementor(increment):
867 return lambda x, n=increment: x+n
Fred Drakef6669171998-05-06 19:52:49 +0000868\end{verbatim}
869
Fred Drake020f8c01998-07-28 19:32:59 +0000870\section{Expression lists\label{exprlists}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000871\indexii{expression}{list}
Fred Drakef6669171998-05-06 19:52:49 +0000872
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000873\begin{verbatim}
874expression_list: expression ("," expression)* [","]
875\end{verbatim}
Fred Drakef6669171998-05-06 19:52:49 +0000876
Fred Drakec009d192000-04-25 21:09:10 +0000877An expression list containing at least one comma yields a
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000878tuple. The length of the tuple is the number of expressions in the
879list. The expressions are evaluated from left to right.
Fred Drakef6669171998-05-06 19:52:49 +0000880\obindex{tuple}
881
882The trailing comma is required only to create a single tuple (a.k.a. a
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000883\emph{singleton}); it is optional in all other cases. A single
Fred Drakec009d192000-04-25 21:09:10 +0000884expression without a trailing comma doesn't create a
885tuple, but rather yields the value of that expression.
Fred Drakef6669171998-05-06 19:52:49 +0000886(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000887\code{()}.)
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000888\indexii{trailing}{comma}
Fred Drakef6669171998-05-06 19:52:49 +0000889
Fred Draked09120b1999-04-29 16:43:42 +0000890
Fred Drake020f8c01998-07-28 19:32:59 +0000891\section{Summary\label{summary}}
Fred Drakef6669171998-05-06 19:52:49 +0000892
Fred Draked09120b1999-04-29 16:43:42 +0000893The following table summarizes the operator
894precedences\indexii{operator}{precedence} in Python, from lowest
895precedence (least binding) to highest precedence (most binding).
896Operators in the same box have the same precedence. Unless the syntax
897is explicitly given, operators are binary. Operators in the same box
898group left to right (except for comparisons, which chain from left to
899right --- see above).
Fred Drakef6669171998-05-06 19:52:49 +0000900
Fred Draked09120b1999-04-29 16:43:42 +0000901\begin{tableii}{c|l}{textrm}{Operator}{Description}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000902 \lineii{\keyword{lambda}} {Lambda expression}
903 \hline
904 \lineii{\keyword{or}} {Boolean OR}
905 \hline
906 \lineii{\keyword{and}} {Boolean AND}
907 \hline
908 \lineii{\keyword{not} \var{x}} {Boolean NOT}
909 \hline
910 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
911 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
912 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
Fred Drake9beee801998-10-21 00:44:49 +0000913 \code{<>}, \code{!=}, \code{==}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000914 {Comparisons}
915 \hline
916 \lineii{\code{|}} {Bitwise OR}
917 \hline
918 \lineii{\code{\^}} {Bitwise XOR}
919 \hline
920 \lineii{\code{\&}} {Bitwise AND}
921 \hline
922 \lineii{\code{<<}, \code{>>}} {Shifts}
923 \hline
924 \lineii{\code{+}, \code{-}}{Addition and subtraction}
925 \hline
Fred Drake9beee801998-10-21 00:44:49 +0000926 \lineii{\code{*}, \code{/}, \code{\%}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000927 {Multiplication, division, remainder}
928 \hline
929 \lineii{\code{**}} {Exponentiation}
930 \hline
931 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
932 \lineii{\code{\~\var{x}}} {Bitwise not}
933 \hline
934 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
935 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
936 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
937 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
Fred Draked09120b1999-04-29 16:43:42 +0000938 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000939 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
940 \lineii{\code{[\var{expressions}\ldots]}} {List display}
941 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
942 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
943\end{tableii}