blob: f6d3b9cd9f3c29278949b9aaefca29f87ad0b850 [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 Montanaro46dfa5f2000-08-22 02:43:07 +0000167single expression followed by at least one "for" clause and zero or more
168"for" or "if" clauses. In this
Skip Montanaro803d6e52000-08-12 18:09:51 +0000169case, the elements of the new list are those that would be produced
170by considering each of the "for" or "if" clauses a block, nesting from
171left to right, and evaluating the expression to produce a list element
172each time the innermost block is reached.
Fred Drakef6669171998-05-06 19:52:49 +0000173\obindex{list}
Fred Drakef6669171998-05-06 19:52:49 +0000174\indexii{empty}{list}
175
Fred Drake020f8c01998-07-28 19:32:59 +0000176\subsection{Dictionary displays\label{dict}}
Fred Drakef6669171998-05-06 19:52:49 +0000177\indexii{dictionary}{display}
178
179A dictionary display is a possibly empty series of key/datum pairs
180enclosed in curly braces:
181\index{key}
182\index{datum}
183\index{key/datum pair}
184
185\begin{verbatim}
186dict_display: "{" [key_datum_list] "}"
187key_datum_list: key_datum ("," key_datum)* [","]
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000188key_datum: expression ":" expression
Fred Drakef6669171998-05-06 19:52:49 +0000189\end{verbatim}
190
191A dictionary display yields a new dictionary object.
192\obindex{dictionary}
193
194The key/datum pairs are evaluated from left to right to define the
195entries of the dictionary: each key object is used as a key into the
196dictionary to store the corresponding datum.
197
198Restrictions on the types of the key values are listed earlier in
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000199section \ref{types}. (To summarize,the key type should be hashable,
200which excludes all mutable objects.) Clashes between duplicate keys
201are not detected; the last datum (textually rightmost in the display)
202stored for a given key value prevails.
Fred Drakee15956b2000-04-03 04:51:13 +0000203\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000204
Fred Drake020f8c01998-07-28 19:32:59 +0000205\subsection{String conversions\label{string-conversions}}
Fred Drakef6669171998-05-06 19:52:49 +0000206\indexii{string}{conversion}
207\indexii{reverse}{quotes}
208\indexii{backward}{quotes}
209\index{back-quotes}
210
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000211A string conversion is an expression list enclosed in reverse (a.k.a.
Fred Drakef6669171998-05-06 19:52:49 +0000212backward) quotes:
213
214\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000215string_conversion: "`" expression_list "`"
Fred Drakef6669171998-05-06 19:52:49 +0000216\end{verbatim}
217
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000218A string conversion evaluates the contained expression list and
Fred Drakef6669171998-05-06 19:52:49 +0000219converts the resulting object into a string according to rules
220specific to its type.
221
Fred Drake5c07d9b1998-05-14 19:37:06 +0000222If the object is a string, a number, \code{None}, or a tuple, list or
Fred Drakef6669171998-05-06 19:52:49 +0000223dictionary containing only objects whose type is one of these, the
224resulting string is a valid Python expression which can be passed to
Fred Drake5c07d9b1998-05-14 19:37:06 +0000225the built-in function \function{eval()} to yield an expression with the
Fred Drakef6669171998-05-06 19:52:49 +0000226same value (or an approximation, if floating point numbers are
227involved).
228
229(In particular, converting a string adds quotes around it and converts
230``funny'' characters to escape sequences that are safe to print.)
231
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000232It is illegal to attempt to convert recursive objects (e.g., lists or
Fred Drakef6669171998-05-06 19:52:49 +0000233dictionaries that contain a reference to themselves, directly or
234indirectly.)
235\obindex{recursive}
236
Fred Drake5c07d9b1998-05-14 19:37:06 +0000237The built-in function \function{repr()} performs exactly the same
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000238conversion in its argument as enclosing it in parentheses and reverse
239quotes does. The built-in function \function{str()} performs a
240similar but more user-friendly conversion.
Fred Drakef6669171998-05-06 19:52:49 +0000241\bifuncindex{repr}
242\bifuncindex{str}
243
Fred Drake020f8c01998-07-28 19:32:59 +0000244\section{Primaries\label{primaries}}
Fred Drakef6669171998-05-06 19:52:49 +0000245\index{primary}
246
247Primaries represent the most tightly bound operations of the language.
248Their syntax is:
249
250\begin{verbatim}
251primary: atom | attributeref | subscription | slicing | call
252\end{verbatim}
253
Fred Drake020f8c01998-07-28 19:32:59 +0000254\subsection{Attribute references\label{attribute-references}}
Fred Drakef6669171998-05-06 19:52:49 +0000255\indexii{attribute}{reference}
256
257An attribute reference is a primary followed by a period and a name:
258
259\begin{verbatim}
260attributeref: primary "." identifier
261\end{verbatim}
262
263The primary must evaluate to an object of a type that supports
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000264attribute references, e.g., a module or a list. This object is then
Fred Drakef6669171998-05-06 19:52:49 +0000265asked to produce the attribute whose name is the identifier. If this
Fred Drake5c07d9b1998-05-14 19:37:06 +0000266attribute is not available, the exception
267\exception{AttributeError}\exindex{AttributeError} is raised.
268Otherwise, the type and value of the object produced is determined by
269the object. Multiple evaluations of the same attribute reference may
270yield different objects.
Fred Drakef6669171998-05-06 19:52:49 +0000271\obindex{module}
272\obindex{list}
273
Fred Drake020f8c01998-07-28 19:32:59 +0000274\subsection{Subscriptions\label{subscriptions}}
Fred Drakef6669171998-05-06 19:52:49 +0000275\index{subscription}
276
277A subscription selects an item of a sequence (string, tuple or list)
278or mapping (dictionary) object:
279\obindex{sequence}
280\obindex{mapping}
281\obindex{string}
282\obindex{tuple}
283\obindex{list}
284\obindex{dictionary}
285\indexii{sequence}{item}
286
287\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000288subscription: primary "[" expression_list "]"
Fred Drakef6669171998-05-06 19:52:49 +0000289\end{verbatim}
290
291The primary must evaluate to an object of a sequence or mapping type.
292
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000293If the primary is a mapping, the expression list must evaluate to an
294object whose value is one of the keys of the mapping, and the
295subscription selects the value in the mapping that corresponds to that
296key. (The expression list is a tuple except if it has exactly one
297item.)
Fred Drakef6669171998-05-06 19:52:49 +0000298
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000299If the primary is a sequence, the expression (list) must evaluate to a
300plain integer. If this value is negative, the length of the sequence
301is added to it (so that, e.g., \code{x[-1]} selects the last item of
302\code{x}.) The resulting value must be a nonnegative integer less
303than the number of items in the sequence, and the subscription selects
304the item whose index is that value (counting from zero).
Fred Drakef6669171998-05-06 19:52:49 +0000305
306A string's items are characters. A character is not a separate data
307type but a string of exactly one character.
308\index{character}
309\indexii{string}{item}
310
Fred Drake020f8c01998-07-28 19:32:59 +0000311\subsection{Slicings\label{slicings}}
Fred Drakef6669171998-05-06 19:52:49 +0000312\index{slicing}
313\index{slice}
314
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000315A slicing selects a range of items in a sequence object (e.g., a
316string, tuple or list). Slicings may be used as expressions or as
317targets in assignment or del statements. The syntax for a slicing:
Fred Drakef6669171998-05-06 19:52:49 +0000318\obindex{sequence}
319\obindex{string}
320\obindex{tuple}
321\obindex{list}
322
323\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000324slicing: simple_slicing | extended_slicing
325simple_slicing: primary "[" short_slice "]"
326extended_slicing: primary "[" slice_list "]"
327slice_list: slice_item ("," slice_item)* [","]
328slice_item: expression | proper_slice | ellipsis
329proper_slice: short_slice | long_slice
330short_slice: [lower_bound] ":" [upper_bound]
331long_slice: short_slice ":" [stride]
332lower_bound: expression
333upper_bound: expression
334stride: expression
335ellipsis: "..."
Fred Drakef6669171998-05-06 19:52:49 +0000336\end{verbatim}
337
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000338There is ambiguity in the formal syntax here: anything that looks like
339an expression list also looks like a slice list, so any subscription
340can be interpreted as a slicing. Rather than further complicating the
341syntax, this is disambiguated by defining that in this case the
342interpretation as a subscription takes priority over the
343interpretation as a slicing (this is the case if the slice list
344contains no proper slice nor ellipses). Similarly, when the slice
345list has exactly one short slice and no trailing comma, the
346interpretation as a simple slicing takes priority over that as an
347extended slicing.\indexii{extended}{slicing}
348
349The semantics for a simple slicing are as follows. The primary must
350evaluate to a sequence object. The lower and upper bound expressions,
351if present, must evaluate to plain integers; defaults are zero and the
Fred Drakee15956b2000-04-03 04:51:13 +0000352\code{sys.maxint}, respectively. If either bound is negative, the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000353sequence's length is added to it. The slicing now selects all items
354with index \var{k} such that
Fred Drakef6669171998-05-06 19:52:49 +0000355\code{\var{i} <= \var{k} < \var{j}} where \var{i}
356and \var{j} are the specified lower and upper bounds. This may be an
357empty sequence. It is not an error if \var{i} or \var{j} lie outside the
358range of valid indexes (such items don't exist so they aren't
359selected).
360
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000361The semantics for an extended slicing are as follows. The primary
362must evaluate to a mapping object, and it is indexed with a key that
363is constructed from the slice list, as follows. If the slice list
364contains at least one comma, the key is a tuple containing the
365conversion of the slice items; otherwise, the conversion of the lone
366slice item is the key. The conversion of a slice item that is an
367expression is that expression. The conversion of an ellipsis slice
368item is the built-in \code{Ellipsis} object. The conversion of a
369proper slice is a slice object (see section \ref{types}) whose
Fred Drakeea81edf1998-11-25 17:51:15 +0000370\member{start}, \member{stop} and \member{step} attributes are the
371values of the expressions given as lower bound, upper bound and
372stride, respectively, substituting \code{None} for missing
373expressions.
Fred Drake99cd5731999-02-12 20:40:09 +0000374\withsubitem{(slice object attribute)}{\ttindex{start}
375 \ttindex{stop}\ttindex{step}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000376
Fred Drake020f8c01998-07-28 19:32:59 +0000377\subsection{Calls\label{calls}}
Fred Drakef6669171998-05-06 19:52:49 +0000378\index{call}
379
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000380A call calls a callable object (e.g., a function) with a possibly empty
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000381series of arguments:
Fred Drakef6669171998-05-06 19:52:49 +0000382\obindex{callable}
383
384\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000385call: primary "(" [argument_list [","]] ")"
386argument_list: positional_arguments ["," keyword_arguments]
387 | keyword_arguments
388positional_arguments: expression ("," expression)*
389keyword_arguments: keyword_item ("," keyword_item)*
390keyword_item: identifier "=" expression
Fred Drakef6669171998-05-06 19:52:49 +0000391\end{verbatim}
392
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000393A trailing comma may be present after an argument list but does not
394affect the semantics.
395
Fred Drakef6669171998-05-06 19:52:49 +0000396The primary must evaluate to a callable object (user-defined
397functions, built-in functions, methods of built-in objects, class
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000398objects, methods of class instances, and certain class instances
399themselves are callable; extensions may define additional callable
400object types). All argument expressions are evaluated before the call
401is attempted. Please refer to section \ref{function} for the syntax
402of formal parameter lists.
403
404If keyword arguments are present, they are first converted to
405positional arguments, as follows. First, a list of unfilled slots is
406created for the formal parameters. If there are N positional
407arguments, they are placed in the first N slots. Next, for each
408keyword argument, the identifier is used to determine the
409corresponding slot (if the identifier is the same as the first formal
410parameter name, the first slot is used, and so on). If the slot is
411already filled, a \exception{TypeError} exception is raised.
412Otherwise, the value of the argument is placed in the slot, filling it
413(even if the expression is \code{None}, it fills the slot). When all
414arguments have been processed, the slots that are still unfilled are
415filled with the corresponding default value from the function
416definition. (Default values are calculated, once, when the function
417is defined; thus, a mutable object such as a list or dictionary used
418as default value will be shared by all calls that don't specify an
419argument value for the corresponding slot; this should usually be
420avoided.) If there are any unfilled slots for which no default value
421is specified, a \exception{TypeError} exception is raised. Otherwise,
422the list of filled slots is used as the argument list for the call.
423
424If there are more positional arguments than there are formal parameter
425slots, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000426parameter using the syntax \samp{*identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000427case, that formal parameter receives a tuple containing the excess
428positional arguments (or an empty tuple if there were no excess
429positional arguments).
430
431If any keyword argument does not correspond to a formal parameter
432name, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000433parameter using the syntax \samp{**identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000434case, that formal parameter receives a dictionary containing the
435excess keyword arguments (using the keywords as keys and the argument
436values as corresponding values), or a (new) empty dictionary if there
437were no excess keyword arguments.
438
Fred Drakeea81edf1998-11-25 17:51:15 +0000439Formal parameters using the syntax \samp{*identifier} or
440\samp{**identifier} cannot be used as positional argument slots or
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000441as keyword argument names. Formal parameters using the syntax
Fred Drakeea81edf1998-11-25 17:51:15 +0000442\samp{(sublist)} cannot be used as keyword argument names; the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000443outermost sublist corresponds to a single unnamed argument slot, and
444the argument value is assigned to the sublist using the usual tuple
445assignment rules after all other parameter processing is done.
Fred Drakef6669171998-05-06 19:52:49 +0000446
Fred Drake5c07d9b1998-05-14 19:37:06 +0000447A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000448raises an exception. How this value is computed depends on the type
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000449of the callable object.
450
451If it is---
Fred Drakef6669171998-05-06 19:52:49 +0000452
453\begin{description}
454
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000455\item[a user-defined function:] The code block for the function is
Fred Drakef6669171998-05-06 19:52:49 +0000456executed, passing it the argument list. The first thing the code
457block will do is bind the formal parameters to the arguments; this is
458described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000459\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000460function call.
461\indexii{function}{call}
462\indexiii{user-defined}{function}{call}
463\obindex{user-defined function}
464\obindex{function}
465
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000466\item[a built-in function or method:] The result is up to the
Fred Drake3d83fc32000-07-31 20:08:23 +0000467interpreter; see the \citetitle[../lib/built-in-funcs.html]{Python
468Library Reference} for the descriptions of built-in functions and
469methods.
Fred Drakef6669171998-05-06 19:52:49 +0000470\indexii{function}{call}
471\indexii{built-in function}{call}
472\indexii{method}{call}
473\indexii{built-in method}{call}
474\obindex{built-in method}
475\obindex{built-in function}
476\obindex{method}
477\obindex{function}
478
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000479\item[a class object:] A new instance of that class is returned.
Fred Drakef6669171998-05-06 19:52:49 +0000480\obindex{class}
481\indexii{class object}{call}
482
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000483\item[a class instance method:] The corresponding user-defined
Fred Drakef6669171998-05-06 19:52:49 +0000484function is called, with an argument list that is one longer than the
485argument list of the call: the instance becomes the first argument.
486\obindex{class instance}
487\obindex{instance}
Fred Drakef6669171998-05-06 19:52:49 +0000488\indexii{class instance}{call}
489
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000490\item[a class instance:] The class must define a \method{__call__()}
491method; the effect is then the same as if that method was called.
492\indexii{instance}{call}
Fred Drakeea81edf1998-11-25 17:51:15 +0000493\withsubitem{(object method)}{\ttindex{__call__()}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000494
Fred Drakef6669171998-05-06 19:52:49 +0000495\end{description}
496
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000497
Fred Drake020f8c01998-07-28 19:32:59 +0000498\section{The power operator\label{power}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000499
500The power operator binds more tightly than unary operators on its
501left; it binds less tightly than unary operators on its right. The
502syntax is:
503
504\begin{verbatim}
505power: primary ["**" u_expr]
506\end{verbatim}
507
508Thus, in an unparenthesized sequence of power and unary operators, the
509operators are evaluated from right to left (this does not constrain
510the evaluation order for the operands).
511
512The power operator has the same semantics as the built-in
513\function{pow()} function, when called with two arguments: it yields
514its left argument raised to the power of its right argument. The
515numeric arguments are first converted to a common type. The result
516type is that of the arguments after coercion; if the result is not
517expressible in that type (as in raising an integer to a negative
518power, or a negative floating point number to a broken power), a
519\exception{TypeError} exception is raised.
520
521
Fred Drakee15956b2000-04-03 04:51:13 +0000522\section{Unary arithmetic operations \label{unary}}
Fred Drakef6669171998-05-06 19:52:49 +0000523\indexiii{unary}{arithmetic}{operation}
524\indexiii{unary}{bit-wise}{operation}
525
526All unary arithmetic (and bit-wise) operations have the same priority:
527
528\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000529u_expr: power | "-" u_expr | "+" u_expr | "~" u_expr
Fred Drakef6669171998-05-06 19:52:49 +0000530\end{verbatim}
531
Fred Drake5c07d9b1998-05-14 19:37:06 +0000532The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000533numeric argument.
534\index{negation}
535\index{minus}
536
Fred Drake5c07d9b1998-05-14 19:37:06 +0000537The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000538unchanged.
539\index{plus}
540
Fred Drakee15956b2000-04-03 04:51:13 +0000541The unary \code{\~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000542of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000543\code{x} is defined as \code{-(x+1)}. It only applies to integral
544numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000545\index{inversion}
546
547In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000548a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000549\exindex{TypeError}
550
Fred Drake020f8c01998-07-28 19:32:59 +0000551\section{Binary arithmetic operations\label{binary}}
Fred Drakef6669171998-05-06 19:52:49 +0000552\indexiii{binary}{arithmetic}{operation}
553
554The binary arithmetic operations have the conventional priority
555levels. Note that some of these operations also apply to certain
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000556non-numeric types. Apart from the power operator, there are only two
557levels, one for multiplicative operators and one for additive
Fred Drakef6669171998-05-06 19:52:49 +0000558operators:
559
560\begin{verbatim}
561m_expr: u_expr | m_expr "*" u_expr
562 | m_expr "/" u_expr | m_expr "%" u_expr
563a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
564\end{verbatim}
565
Fred Drake5c07d9b1998-05-14 19:37:06 +0000566The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000567arguments. The arguments must either both be numbers, or one argument
568must be a plain integer and the other must be a sequence. In the
569former case, the numbers are converted to a common type and then
570multiplied together. In the latter case, sequence repetition is
571performed; a negative repetition factor yields an empty sequence.
572\index{multiplication}
573
Fred Drake5c07d9b1998-05-14 19:37:06 +0000574The \code{/} (division) operator yields the quotient of its
Fred Drakef6669171998-05-06 19:52:49 +0000575arguments. The numeric arguments are first converted to a common
576type. Plain or long integer division yields an integer of the same
577type; the result is that of mathematical division with the `floor'
578function applied to the result. Division by zero raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000579\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000580\exindex{ZeroDivisionError}
581\index{division}
582
Fred Drake5c07d9b1998-05-14 19:37:06 +0000583The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000584division of the first argument by the second. The numeric arguments
585are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000586the \exception{ZeroDivisionError} exception. The arguments may be floating
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000587point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000588\code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
589yields a result with the same sign as its second operand (or zero);
590the absolute value of the result is strictly smaller than the second
591operand.
Fred Drakef6669171998-05-06 19:52:49 +0000592\index{modulo}
593
594The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000595following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
596modulo are also connected with the built-in function \function{divmod()}:
597\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Fred Drake1ea7c751999-05-06 14:46:35 +0000598floating point and complex numbers; there similar identities hold
599approximately where \code{x/y} is replaced by \code{floor(x/y)}) or
600\code{floor(x/y) - 1} (for floats),\footnote{
601 If x is very close to an exact integer multiple of y, it's
602 possible for \code{floor(x/y)} to be one larger than
603 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
604 the latter result, in order to preserve that \code{divmod(x,y)[0]
605 * y + x \%{} y} be very close to \code{x}.
606} or \code{floor((x/y).real)} (for
607complex).
Fred Drakef6669171998-05-06 19:52:49 +0000608
Fred Drake5c07d9b1998-05-14 19:37:06 +0000609The \code{+} (addition) operator yields the sum of its arguments.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000610The arguments must either both be numbers or both sequences of the
Fred Drakef6669171998-05-06 19:52:49 +0000611same type. In the former case, the numbers are converted to a common
612type and then added together. In the latter case, the sequences are
613concatenated.
614\index{addition}
615
Fred Drake5c07d9b1998-05-14 19:37:06 +0000616The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000617arguments. The numeric arguments are first converted to a common
618type.
619\index{subtraction}
620
Fred Drake020f8c01998-07-28 19:32:59 +0000621\section{Shifting operations\label{shifting}}
Fred Drakef6669171998-05-06 19:52:49 +0000622\indexii{shifting}{operation}
623
624The shifting operations have lower priority than the arithmetic
625operations:
626
627\begin{verbatim}
628shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
629\end{verbatim}
630
631These operators accept plain or long integers as arguments. The
632arguments are converted to a common type. They shift the first
633argument to the left or right by the number of bits given by the
634second argument.
635
636A right shift by \var{n} bits is defined as division by
637\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
638multiplication with \code{pow(2,\var{n})}; for plain integers there is
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000639no overflow check so in that case the operation drops bits and flips
640the sign if the result is not less than \code{pow(2,31)} in absolute
641value. Negative shift counts raise a \exception{ValueError}
642exception.
Fred Drakef6669171998-05-06 19:52:49 +0000643\exindex{ValueError}
644
Fred Drake020f8c01998-07-28 19:32:59 +0000645\section{Binary bit-wise operations\label{bitwise}}
Fred Drakef6669171998-05-06 19:52:49 +0000646\indexiii{binary}{bit-wise}{operation}
647
648Each of the three bitwise operations has a different priority level:
649
650\begin{verbatim}
651and_expr: shift_expr | and_expr "&" shift_expr
652xor_expr: and_expr | xor_expr "^" and_expr
653or_expr: xor_expr | or_expr "|" xor_expr
654\end{verbatim}
655
Fred Drake5c07d9b1998-05-14 19:37:06 +0000656The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000657must be plain or long integers. The arguments are converted to a
658common type.
659\indexii{bit-wise}{and}
660
Fred Drake5c07d9b1998-05-14 19:37:06 +0000661The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000662arguments, which must be plain or long integers. The arguments are
663converted to a common type.
664\indexii{bit-wise}{xor}
665\indexii{exclusive}{or}
666
Fred Drake5c07d9b1998-05-14 19:37:06 +0000667The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000668arguments, which must be plain or long integers. The arguments are
669converted to a common type.
670\indexii{bit-wise}{or}
671\indexii{inclusive}{or}
672
Fred Drake020f8c01998-07-28 19:32:59 +0000673\section{Comparisons\label{comparisons}}
Fred Drakef6669171998-05-06 19:52:49 +0000674\index{comparison}
675
Fred Drake5c07d9b1998-05-14 19:37:06 +0000676Contrary to \C, all comparison operations in Python have the same
Fred Drakef6669171998-05-06 19:52:49 +0000677priority, which is lower than that of any arithmetic, shifting or
Fred Drake5c07d9b1998-05-14 19:37:06 +0000678bitwise operation. Also contrary to \C, expressions like
679\code{a < b < c} have the interpretation that is conventional in
Fred Drakef6669171998-05-06 19:52:49 +0000680mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000681\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000682
683\begin{verbatim}
684comparison: or_expr (comp_operator or_expr)*
685comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
686\end{verbatim}
687
Fred Drake5c07d9b1998-05-14 19:37:06 +0000688Comparisons yield integer values: \code{1} for true, \code{0} for false.
Fred Drakef6669171998-05-06 19:52:49 +0000689
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000690Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
Fred Drakef6669171998-05-06 19:52:49 +0000691equivalent to \code{x < y and y <= z}, except that \code{y} is
692evaluated only once (but in both cases \code{z} is not evaluated at all
693when \code{x < y} is found to be false).
694\indexii{chaining}{comparisons}
695
696Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
697expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
698operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000699to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
Fred Drakef6669171998-05-06 19:52:49 +0000700\var{y opy z}, except that each expression is evaluated at most once.
701
702Note that \var{a opa b opb c} doesn't imply any kind of comparison
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000703between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
Fred Drakef6669171998-05-06 19:52:49 +0000704perfectly legal (though perhaps not pretty).
705
Fred Drake5c07d9b1998-05-14 19:37:06 +0000706The forms \code{<>} and \code{!=} are equivalent; for consistency with
707C, \code{!=} is preferred; where \code{!=} is mentioned below
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000708\code{<>} is also acceptable. At some point in the (far) future,
709\code{<>} may become obsolete.
Fred Drakef6669171998-05-06 19:52:49 +0000710
Fred Draked03268f1998-11-25 19:23:33 +0000711The operators \texttt{"<", ">", "==", ">=", "<="}, and \texttt{"!="} compare
Fred Drakef6669171998-05-06 19:52:49 +0000712the values of two objects. The objects needn't have the same type.
713If both are numbers, they are coverted to a common type. Otherwise,
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000714objects of different types \emph{always} compare unequal, and are
Fred Drakef6669171998-05-06 19:52:49 +0000715ordered consistently but arbitrarily.
716
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000717(This unusual definition of comparison was used to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000718definition of operations like sorting and the \keyword{in} and
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000719\keyword{not in} operators. In the future, the comparison rules for
720objects of different types are likely to change.)
Fred Drakef6669171998-05-06 19:52:49 +0000721
722Comparison of objects of the same type depends on the type:
723
724\begin{itemize}
725
726\item
727Numbers are compared arithmetically.
728
729\item
730Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +0000731(the result of the built-in function \function{ord()}) of their
732characters.
Fred Drakef6669171998-05-06 19:52:49 +0000733
734\item
735Tuples and lists are compared lexicographically using comparison of
736corresponding items.
737
738\item
739Mappings (dictionaries) are compared through lexicographic
Fred Drakeb55ce1e1999-04-05 21:32:52 +0000740comparison of their sorted (key, value) lists.\footnote{
741This is expensive since it requires sorting the keys first,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000742but it is about the only sensible definition. An earlier version of
743Python compared dictionaries by identity only, but this caused
744surprises because people expected to be able to test a dictionary for
745emptiness by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +0000746
747\item
748Most other types compare unequal unless they are the same object;
749the choice whether one object is considered smaller or larger than
750another one is made arbitrarily but consistently within one
751execution of a program.
752
753\end{itemize}
754
Fred Drake7399b9e2000-07-11 19:43:47 +0000755The operators \keyword{in} and \keyword{not in} test for set
756membership: every type can define membership in whatever way is
757appropriate. Traditionally, this interface has been tightly bound
758the sequence interface, which is related in that presence in a sequence
759can be usefully interpreted as membership in a set.
760
761For the list, tuple types, \code{\var{x} in \var{y}} is true if and only
762if there exists such an index \var{i} such that
763\code{var{x} == \var{y}[\var{i}]} is true.
764
765For the Unicode and string types, \code{\var{x} in \var{y}} is true if and only
766if there exists such an index \var{i} such that
767\code{var{x} == \var{y}[\var{i}]} is true. If \code{\var{x}} is not
768a string of length \code{1} or a unicode object of length \code{1},
769a \exception{TypeError} exception is raised.
770
771For user-defined classes which define the \method{__contains__()} method,
772\code{\var{x} in \var{y}} is true if and only if
773\code{\var{y}.__contains__(\var{x})} is true.
774
775For user-defined classes which do not define \method{__contains__()} and
776do define \var{__getitem__}, \code{\var{x} in \var{y}} is true if and only
777if there is a non-negative integer index \var{i} such that
778\code{\var{x} == \var{y}[\var{i}]}, and all lower integer indices
779do not raise \exception{IndexError} exception. (If any other exception
780is raised, it is as if \keyword{in} raised that exception).
781
782The operator \keyword{not in} is defined to have the inverse true value
783of \keyword{in}.
Fred Drakef6669171998-05-06 19:52:49 +0000784\opindex{in}
785\opindex{not in}
786\indexii{membership}{test}
787\obindex{sequence}
788
Fred Drake5c07d9b1998-05-14 19:37:06 +0000789The operators \keyword{is} and \keyword{is not} test for object identity:
790\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
791are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +0000792truth value.
793\opindex{is}
794\opindex{is not}
795\indexii{identity}{test}
796
Fred Drake020f8c01998-07-28 19:32:59 +0000797\section{Boolean operations\label{Booleans}}
Fred Drakef6669171998-05-06 19:52:49 +0000798\indexii{Boolean}{operation}
799
800Boolean operations have the lowest priority of all Python operations:
801
802\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000803expression: or_test | lambda_form
Fred Drakef6669171998-05-06 19:52:49 +0000804or_test: and_test | or_test "or" and_test
805and_test: not_test | and_test "and" not_test
806not_test: comparison | "not" not_test
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000807lambda_form: "lambda" [parameter_list]: expression
Fred Drakef6669171998-05-06 19:52:49 +0000808\end{verbatim}
809
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000810In the context of Boolean operations, and also when expressions are
Fred Drakef6669171998-05-06 19:52:49 +0000811used by control flow statements, the following values are interpreted
Fred Drake5c07d9b1998-05-14 19:37:06 +0000812as false: \code{None}, numeric zero of all types, empty sequences
Fred Drakef6669171998-05-06 19:52:49 +0000813(strings, tuples and lists), and empty mappings (dictionaries). All
814other values are interpreted as true.
815
Fred Drake5c07d9b1998-05-14 19:37:06 +0000816The operator \keyword{not} yields \code{1} if its argument is false,
817\code{0} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +0000818\opindex{not}
819
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000820The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000821\var{x} is false, its value is returned; otherwise, \var{y} is
822evaluated and the resulting value is returned.
823\opindex{and}
824
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000825The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000826\var{x} is true, its value is returned; otherwise, \var{y} is
827evaluated and the resulting value is returned.
828\opindex{or}
829
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000830(Note that neither \keyword{and} nor \keyword{or} restrict the value
Fred Drake5c07d9b1998-05-14 19:37:06 +0000831and type they return to \code{0} and \code{1}, but rather return the
832last evaluated argument.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000833This is sometimes useful, e.g., if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +0000834replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +0000835\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +0000836invent a value anyway, it does not bother to return a value of the
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000837same type as its argument, so e.g., \code{not 'foo'} yields \code{0},
Fred Drake5c07d9b1998-05-14 19:37:06 +0000838not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +0000839
840Lambda forms (lambda expressions) have the same syntactic position as
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000841expressions. They are a shorthand to create anonymous functions; the
842expression \code{lambda \var{arguments}: \var{expression}}
Fred Drakef6669171998-05-06 19:52:49 +0000843yields a function object that behaves virtually identical to one
844defined with
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000845
846\begin{verbatim}
847def name(arguments):
848 return expression
849\end{verbatim}
850
851See section \ref{function} for the syntax of parameter lists. Note
852that functions created with lambda forms cannot contain statements.
Fred Drakef6669171998-05-06 19:52:49 +0000853\label{lambda}
854\indexii{lambda}{expression}
855\indexii{lambda}{form}
856\indexii{anonmymous}{function}
857
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000858\strong{Programmer's note:} a lambda form defined inside a function
859has no access to names defined in the function's namespace. This is
860because Python has only two scopes: local and global. A common
861work-around is to use default argument values to pass selected
862variables into the lambda's namespace, e.g.:
Fred Drakef6669171998-05-06 19:52:49 +0000863
864\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000865def make_incrementor(increment):
866 return lambda x, n=increment: x+n
Fred Drakef6669171998-05-06 19:52:49 +0000867\end{verbatim}
868
Fred Drake020f8c01998-07-28 19:32:59 +0000869\section{Expression lists\label{exprlists}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000870\indexii{expression}{list}
Fred Drakef6669171998-05-06 19:52:49 +0000871
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000872\begin{verbatim}
873expression_list: expression ("," expression)* [","]
874\end{verbatim}
Fred Drakef6669171998-05-06 19:52:49 +0000875
Fred Drakec009d192000-04-25 21:09:10 +0000876An expression list containing at least one comma yields a
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000877tuple. The length of the tuple is the number of expressions in the
878list. The expressions are evaluated from left to right.
Fred Drakef6669171998-05-06 19:52:49 +0000879\obindex{tuple}
880
881The trailing comma is required only to create a single tuple (a.k.a. a
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000882\emph{singleton}); it is optional in all other cases. A single
Fred Drakec009d192000-04-25 21:09:10 +0000883expression without a trailing comma doesn't create a
884tuple, but rather yields the value of that expression.
Fred Drakef6669171998-05-06 19:52:49 +0000885(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000886\code{()}.)
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000887\indexii{trailing}{comma}
Fred Drakef6669171998-05-06 19:52:49 +0000888
Fred Draked09120b1999-04-29 16:43:42 +0000889
Fred Drake020f8c01998-07-28 19:32:59 +0000890\section{Summary\label{summary}}
Fred Drakef6669171998-05-06 19:52:49 +0000891
Fred Draked09120b1999-04-29 16:43:42 +0000892The following table summarizes the operator
893precedences\indexii{operator}{precedence} in Python, from lowest
894precedence (least binding) to highest precedence (most binding).
895Operators in the same box have the same precedence. Unless the syntax
896is explicitly given, operators are binary. Operators in the same box
897group left to right (except for comparisons, which chain from left to
898right --- see above).
Fred Drakef6669171998-05-06 19:52:49 +0000899
Fred Draked09120b1999-04-29 16:43:42 +0000900\begin{tableii}{c|l}{textrm}{Operator}{Description}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000901 \lineii{\keyword{lambda}} {Lambda expression}
902 \hline
903 \lineii{\keyword{or}} {Boolean OR}
904 \hline
905 \lineii{\keyword{and}} {Boolean AND}
906 \hline
907 \lineii{\keyword{not} \var{x}} {Boolean NOT}
908 \hline
909 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
910 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
911 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
Fred Drake9beee801998-10-21 00:44:49 +0000912 \code{<>}, \code{!=}, \code{==}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000913 {Comparisons}
914 \hline
915 \lineii{\code{|}} {Bitwise OR}
916 \hline
917 \lineii{\code{\^}} {Bitwise XOR}
918 \hline
919 \lineii{\code{\&}} {Bitwise AND}
920 \hline
921 \lineii{\code{<<}, \code{>>}} {Shifts}
922 \hline
923 \lineii{\code{+}, \code{-}}{Addition and subtraction}
924 \hline
Fred Drake9beee801998-10-21 00:44:49 +0000925 \lineii{\code{*}, \code{/}, \code{\%}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000926 {Multiplication, division, remainder}
927 \hline
928 \lineii{\code{**}} {Exponentiation}
929 \hline
930 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
931 \lineii{\code{\~\var{x}}} {Bitwise not}
932 \hline
933 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
934 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
935 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
936 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
Fred Draked09120b1999-04-29 16:43:42 +0000937 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000938 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
939 \lineii{\code{[\var{expressions}\ldots]}} {List display}
940 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
941 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
942\end{tableii}