blob: a7e635153af650db9480c8845a75304ac9cbfa64 [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}
Skip Montanarob6559392000-09-11 16:31:55 +0000150\indexii{list}{comprehensions}
Fred Drakef6669171998-05-06 19:52:49 +0000151
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000152A list display is a possibly empty series of expressions enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000153square brackets:
154
155\begin{verbatim}
Fred Drakea1e214a2000-08-15 17:54:49 +0000156list_display: "[" [listmaker] "]"
Skip Montanaro46dfa5f2000-08-22 02:43:07 +0000157listmaker: expression ( list_for | ( "," expression)* [","] )
Skip Montanaro803d6e52000-08-12 18:09:51 +0000158list_iter: list_for | list_if
159list_for: "for" expression_list "in" testlist [list_iter]
160list_if: "if" test [list_iter]
Fred Drakef6669171998-05-06 19:52:49 +0000161\end{verbatim}
162
Skip Montanaro803d6e52000-08-12 18:09:51 +0000163A list display yields a new list object. Its contents are specified
164by providing either a list of expressions or a list comprehension.
Skip Montanarob6559392000-09-11 16:31:55 +0000165\indexii{list}{comprehensions}
Skip Montanaro803d6e52000-08-12 18:09:51 +0000166When a comma-separated list of expressions is supplied, its elements are
167evaluated from left to right and placed into the list object in that
168order. When a list comprehension is supplied, it consists of a
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000169single expression followed by at least one \keyword{for} clause and zero or
170more \keyword{for} or \keyword{if} clauses. In this
Skip Montanaro803d6e52000-08-12 18:09:51 +0000171case, the elements of the new list are those that would be produced
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000172by considering each of the \keyword{for} or \keyword{if} clauses a block,
173nesting from
Skip Montanaro803d6e52000-08-12 18:09:51 +0000174left to right, and evaluating the expression to produce a list element
175each time the innermost block is reached.
Fred Drakef6669171998-05-06 19:52:49 +0000176\obindex{list}
Fred Drakef6669171998-05-06 19:52:49 +0000177\indexii{empty}{list}
178
Fred Drake020f8c01998-07-28 19:32:59 +0000179\subsection{Dictionary displays\label{dict}}
Fred Drakef6669171998-05-06 19:52:49 +0000180\indexii{dictionary}{display}
181
182A dictionary display is a possibly empty series of key/datum pairs
183enclosed in curly braces:
184\index{key}
185\index{datum}
186\index{key/datum pair}
187
188\begin{verbatim}
189dict_display: "{" [key_datum_list] "}"
190key_datum_list: key_datum ("," key_datum)* [","]
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000191key_datum: expression ":" expression
Fred Drakef6669171998-05-06 19:52:49 +0000192\end{verbatim}
193
194A dictionary display yields a new dictionary object.
195\obindex{dictionary}
196
197The key/datum pairs are evaluated from left to right to define the
198entries of the dictionary: each key object is used as a key into the
199dictionary to store the corresponding datum.
200
201Restrictions on the types of the key values are listed earlier in
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000202section \ref{types}. (To summarize,the key type should be hashable,
203which excludes all mutable objects.) Clashes between duplicate keys
204are not detected; the last datum (textually rightmost in the display)
205stored for a given key value prevails.
Fred Drakee15956b2000-04-03 04:51:13 +0000206\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000207
Fred Drake020f8c01998-07-28 19:32:59 +0000208\subsection{String conversions\label{string-conversions}}
Fred Drakef6669171998-05-06 19:52:49 +0000209\indexii{string}{conversion}
210\indexii{reverse}{quotes}
211\indexii{backward}{quotes}
212\index{back-quotes}
213
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000214A string conversion is an expression list enclosed in reverse (a.k.a.
Fred Drakef6669171998-05-06 19:52:49 +0000215backward) quotes:
216
217\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000218string_conversion: "`" expression_list "`"
Fred Drakef6669171998-05-06 19:52:49 +0000219\end{verbatim}
220
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000221A string conversion evaluates the contained expression list and
Fred Drakef6669171998-05-06 19:52:49 +0000222converts the resulting object into a string according to rules
223specific to its type.
224
Fred Drake5c07d9b1998-05-14 19:37:06 +0000225If the object is a string, a number, \code{None}, or a tuple, list or
Fred Drakef6669171998-05-06 19:52:49 +0000226dictionary containing only objects whose type is one of these, the
227resulting string is a valid Python expression which can be passed to
Fred Drake5c07d9b1998-05-14 19:37:06 +0000228the built-in function \function{eval()} to yield an expression with the
Fred Drakef6669171998-05-06 19:52:49 +0000229same value (or an approximation, if floating point numbers are
230involved).
231
232(In particular, converting a string adds quotes around it and converts
233``funny'' characters to escape sequences that are safe to print.)
234
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000235It is illegal to attempt to convert recursive objects (e.g., lists or
Fred Drakef6669171998-05-06 19:52:49 +0000236dictionaries that contain a reference to themselves, directly or
237indirectly.)
238\obindex{recursive}
239
Fred Drake5c07d9b1998-05-14 19:37:06 +0000240The built-in function \function{repr()} performs exactly the same
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000241conversion in its argument as enclosing it in parentheses and reverse
242quotes does. The built-in function \function{str()} performs a
243similar but more user-friendly conversion.
Fred Drakef6669171998-05-06 19:52:49 +0000244\bifuncindex{repr}
245\bifuncindex{str}
246
Fred Drake020f8c01998-07-28 19:32:59 +0000247\section{Primaries\label{primaries}}
Fred Drakef6669171998-05-06 19:52:49 +0000248\index{primary}
249
250Primaries represent the most tightly bound operations of the language.
251Their syntax is:
252
253\begin{verbatim}
254primary: atom | attributeref | subscription | slicing | call
255\end{verbatim}
256
Fred Drake020f8c01998-07-28 19:32:59 +0000257\subsection{Attribute references\label{attribute-references}}
Fred Drakef6669171998-05-06 19:52:49 +0000258\indexii{attribute}{reference}
259
260An attribute reference is a primary followed by a period and a name:
261
262\begin{verbatim}
263attributeref: primary "." identifier
264\end{verbatim}
265
266The primary must evaluate to an object of a type that supports
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000267attribute references, e.g., a module or a list. This object is then
Fred Drakef6669171998-05-06 19:52:49 +0000268asked to produce the attribute whose name is the identifier. If this
Fred Drake5c07d9b1998-05-14 19:37:06 +0000269attribute is not available, the exception
270\exception{AttributeError}\exindex{AttributeError} is raised.
271Otherwise, the type and value of the object produced is determined by
272the object. Multiple evaluations of the same attribute reference may
273yield different objects.
Fred Drakef6669171998-05-06 19:52:49 +0000274\obindex{module}
275\obindex{list}
276
Fred Drake020f8c01998-07-28 19:32:59 +0000277\subsection{Subscriptions\label{subscriptions}}
Fred Drakef6669171998-05-06 19:52:49 +0000278\index{subscription}
279
280A subscription selects an item of a sequence (string, tuple or list)
281or mapping (dictionary) object:
282\obindex{sequence}
283\obindex{mapping}
284\obindex{string}
285\obindex{tuple}
286\obindex{list}
287\obindex{dictionary}
288\indexii{sequence}{item}
289
290\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000291subscription: primary "[" expression_list "]"
Fred Drakef6669171998-05-06 19:52:49 +0000292\end{verbatim}
293
294The primary must evaluate to an object of a sequence or mapping type.
295
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000296If the primary is a mapping, the expression list must evaluate to an
297object whose value is one of the keys of the mapping, and the
298subscription selects the value in the mapping that corresponds to that
299key. (The expression list is a tuple except if it has exactly one
300item.)
Fred Drakef6669171998-05-06 19:52:49 +0000301
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000302If the primary is a sequence, the expression (list) must evaluate to a
303plain integer. If this value is negative, the length of the sequence
304is added to it (so that, e.g., \code{x[-1]} selects the last item of
305\code{x}.) The resulting value must be a nonnegative integer less
306than the number of items in the sequence, and the subscription selects
307the item whose index is that value (counting from zero).
Fred Drakef6669171998-05-06 19:52:49 +0000308
309A string's items are characters. A character is not a separate data
310type but a string of exactly one character.
311\index{character}
312\indexii{string}{item}
313
Fred Drake020f8c01998-07-28 19:32:59 +0000314\subsection{Slicings\label{slicings}}
Fred Drakef6669171998-05-06 19:52:49 +0000315\index{slicing}
316\index{slice}
317
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000318A slicing selects a range of items in a sequence object (e.g., a
319string, tuple or list). Slicings may be used as expressions or as
320targets in assignment or del statements. The syntax for a slicing:
Fred Drakef6669171998-05-06 19:52:49 +0000321\obindex{sequence}
322\obindex{string}
323\obindex{tuple}
324\obindex{list}
325
326\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000327slicing: simple_slicing | extended_slicing
328simple_slicing: primary "[" short_slice "]"
329extended_slicing: primary "[" slice_list "]"
330slice_list: slice_item ("," slice_item)* [","]
331slice_item: expression | proper_slice | ellipsis
332proper_slice: short_slice | long_slice
333short_slice: [lower_bound] ":" [upper_bound]
334long_slice: short_slice ":" [stride]
335lower_bound: expression
336upper_bound: expression
337stride: expression
338ellipsis: "..."
Fred Drakef6669171998-05-06 19:52:49 +0000339\end{verbatim}
340
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000341There is ambiguity in the formal syntax here: anything that looks like
342an expression list also looks like a slice list, so any subscription
343can be interpreted as a slicing. Rather than further complicating the
344syntax, this is disambiguated by defining that in this case the
345interpretation as a subscription takes priority over the
346interpretation as a slicing (this is the case if the slice list
347contains no proper slice nor ellipses). Similarly, when the slice
348list has exactly one short slice and no trailing comma, the
349interpretation as a simple slicing takes priority over that as an
350extended slicing.\indexii{extended}{slicing}
351
352The semantics for a simple slicing are as follows. The primary must
353evaluate to a sequence object. The lower and upper bound expressions,
354if present, must evaluate to plain integers; defaults are zero and the
Fred Drakee15956b2000-04-03 04:51:13 +0000355\code{sys.maxint}, respectively. If either bound is negative, the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000356sequence's length is added to it. The slicing now selects all items
357with index \var{k} such that
Fred Drakef6669171998-05-06 19:52:49 +0000358\code{\var{i} <= \var{k} < \var{j}} where \var{i}
359and \var{j} are the specified lower and upper bounds. This may be an
360empty sequence. It is not an error if \var{i} or \var{j} lie outside the
361range of valid indexes (such items don't exist so they aren't
362selected).
363
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000364The semantics for an extended slicing are as follows. The primary
365must evaluate to a mapping object, and it is indexed with a key that
366is constructed from the slice list, as follows. If the slice list
367contains at least one comma, the key is a tuple containing the
368conversion of the slice items; otherwise, the conversion of the lone
369slice item is the key. The conversion of a slice item that is an
370expression is that expression. The conversion of an ellipsis slice
371item is the built-in \code{Ellipsis} object. The conversion of a
372proper slice is a slice object (see section \ref{types}) whose
Fred Drakeea81edf1998-11-25 17:51:15 +0000373\member{start}, \member{stop} and \member{step} attributes are the
374values of the expressions given as lower bound, upper bound and
375stride, respectively, substituting \code{None} for missing
376expressions.
Fred Drake99cd5731999-02-12 20:40:09 +0000377\withsubitem{(slice object attribute)}{\ttindex{start}
378 \ttindex{stop}\ttindex{step}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000379
Fred Drake020f8c01998-07-28 19:32:59 +0000380\subsection{Calls\label{calls}}
Fred Drakef6669171998-05-06 19:52:49 +0000381\index{call}
382
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000383A call calls a callable object (e.g., a function) with a possibly empty
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000384series of arguments:
Fred Drakef6669171998-05-06 19:52:49 +0000385\obindex{callable}
386
387\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000388call: primary "(" [argument_list [","]] ")"
389argument_list: positional_arguments ["," keyword_arguments]
390 | keyword_arguments
391positional_arguments: expression ("," expression)*
392keyword_arguments: keyword_item ("," keyword_item)*
393keyword_item: identifier "=" expression
Fred Drakef6669171998-05-06 19:52:49 +0000394\end{verbatim}
395
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000396A trailing comma may be present after an argument list but does not
397affect the semantics.
398
Fred Drakef6669171998-05-06 19:52:49 +0000399The primary must evaluate to a callable object (user-defined
400functions, built-in functions, methods of built-in objects, class
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000401objects, methods of class instances, and certain class instances
402themselves are callable; extensions may define additional callable
403object types). All argument expressions are evaluated before the call
404is attempted. Please refer to section \ref{function} for the syntax
405of formal parameter lists.
406
407If keyword arguments are present, they are first converted to
408positional arguments, as follows. First, a list of unfilled slots is
409created for the formal parameters. If there are N positional
410arguments, they are placed in the first N slots. Next, for each
411keyword argument, the identifier is used to determine the
412corresponding slot (if the identifier is the same as the first formal
413parameter name, the first slot is used, and so on). If the slot is
414already filled, a \exception{TypeError} exception is raised.
415Otherwise, the value of the argument is placed in the slot, filling it
416(even if the expression is \code{None}, it fills the slot). When all
417arguments have been processed, the slots that are still unfilled are
418filled with the corresponding default value from the function
419definition. (Default values are calculated, once, when the function
420is defined; thus, a mutable object such as a list or dictionary used
421as default value will be shared by all calls that don't specify an
422argument value for the corresponding slot; this should usually be
423avoided.) If there are any unfilled slots for which no default value
424is specified, a \exception{TypeError} exception is raised. Otherwise,
425the list of filled slots is used as the argument list for the call.
426
427If there are more positional arguments than there are formal parameter
428slots, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000429parameter using the syntax \samp{*identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000430case, that formal parameter receives a tuple containing the excess
431positional arguments (or an empty tuple if there were no excess
432positional arguments).
433
434If any keyword argument does not correspond to a formal parameter
435name, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000436parameter using the syntax \samp{**identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000437case, that formal parameter receives a dictionary containing the
438excess keyword arguments (using the keywords as keys and the argument
439values as corresponding values), or a (new) empty dictionary if there
440were no excess keyword arguments.
441
Fred Drakeea81edf1998-11-25 17:51:15 +0000442Formal parameters using the syntax \samp{*identifier} or
443\samp{**identifier} cannot be used as positional argument slots or
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000444as keyword argument names. Formal parameters using the syntax
Fred Drakeea81edf1998-11-25 17:51:15 +0000445\samp{(sublist)} cannot be used as keyword argument names; the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000446outermost sublist corresponds to a single unnamed argument slot, and
447the argument value is assigned to the sublist using the usual tuple
448assignment rules after all other parameter processing is done.
Fred Drakef6669171998-05-06 19:52:49 +0000449
Fred Drake5c07d9b1998-05-14 19:37:06 +0000450A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000451raises an exception. How this value is computed depends on the type
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000452of the callable object.
453
454If it is---
Fred Drakef6669171998-05-06 19:52:49 +0000455
456\begin{description}
457
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000458\item[a user-defined function:] The code block for the function is
Fred Drakef6669171998-05-06 19:52:49 +0000459executed, passing it the argument list. The first thing the code
460block will do is bind the formal parameters to the arguments; this is
461described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000462\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000463function call.
464\indexii{function}{call}
465\indexiii{user-defined}{function}{call}
466\obindex{user-defined function}
467\obindex{function}
468
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000469\item[a built-in function or method:] The result is up to the
Fred Drake3d83fc32000-07-31 20:08:23 +0000470interpreter; see the \citetitle[../lib/built-in-funcs.html]{Python
471Library Reference} for the descriptions of built-in functions and
472methods.
Fred Drakef6669171998-05-06 19:52:49 +0000473\indexii{function}{call}
474\indexii{built-in function}{call}
475\indexii{method}{call}
476\indexii{built-in method}{call}
477\obindex{built-in method}
478\obindex{built-in function}
479\obindex{method}
480\obindex{function}
481
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000482\item[a class object:] A new instance of that class is returned.
Fred Drakef6669171998-05-06 19:52:49 +0000483\obindex{class}
484\indexii{class object}{call}
485
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000486\item[a class instance method:] The corresponding user-defined
Fred Drakef6669171998-05-06 19:52:49 +0000487function is called, with an argument list that is one longer than the
488argument list of the call: the instance becomes the first argument.
489\obindex{class instance}
490\obindex{instance}
Fred Drakef6669171998-05-06 19:52:49 +0000491\indexii{class instance}{call}
492
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000493\item[a class instance:] The class must define a \method{__call__()}
494method; the effect is then the same as if that method was called.
495\indexii{instance}{call}
Fred Drakeea81edf1998-11-25 17:51:15 +0000496\withsubitem{(object method)}{\ttindex{__call__()}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000497
Fred Drakef6669171998-05-06 19:52:49 +0000498\end{description}
499
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000500
Fred Drake020f8c01998-07-28 19:32:59 +0000501\section{The power operator\label{power}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000502
503The power operator binds more tightly than unary operators on its
504left; it binds less tightly than unary operators on its right. The
505syntax is:
506
507\begin{verbatim}
508power: primary ["**" u_expr]
509\end{verbatim}
510
511Thus, in an unparenthesized sequence of power and unary operators, the
512operators are evaluated from right to left (this does not constrain
513the evaluation order for the operands).
514
515The power operator has the same semantics as the built-in
516\function{pow()} function, when called with two arguments: it yields
517its left argument raised to the power of its right argument. The
518numeric arguments are first converted to a common type. The result
519type is that of the arguments after coercion; if the result is not
520expressible in that type (as in raising an integer to a negative
521power, or a negative floating point number to a broken power), a
522\exception{TypeError} exception is raised.
523
524
Fred Drakee15956b2000-04-03 04:51:13 +0000525\section{Unary arithmetic operations \label{unary}}
Fred Drakef6669171998-05-06 19:52:49 +0000526\indexiii{unary}{arithmetic}{operation}
527\indexiii{unary}{bit-wise}{operation}
528
529All unary arithmetic (and bit-wise) operations have the same priority:
530
531\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000532u_expr: power | "-" u_expr | "+" u_expr | "~" u_expr
Fred Drakef6669171998-05-06 19:52:49 +0000533\end{verbatim}
534
Fred Drake5c07d9b1998-05-14 19:37:06 +0000535The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000536numeric argument.
537\index{negation}
538\index{minus}
539
Fred Drake5c07d9b1998-05-14 19:37:06 +0000540The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000541unchanged.
542\index{plus}
543
Fred Drakee15956b2000-04-03 04:51:13 +0000544The unary \code{\~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000545of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000546\code{x} is defined as \code{-(x+1)}. It only applies to integral
547numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000548\index{inversion}
549
550In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000551a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000552\exindex{TypeError}
553
Fred Drake020f8c01998-07-28 19:32:59 +0000554\section{Binary arithmetic operations\label{binary}}
Fred Drakef6669171998-05-06 19:52:49 +0000555\indexiii{binary}{arithmetic}{operation}
556
557The binary arithmetic operations have the conventional priority
558levels. Note that some of these operations also apply to certain
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000559non-numeric types. Apart from the power operator, there are only two
560levels, one for multiplicative operators and one for additive
Fred Drakef6669171998-05-06 19:52:49 +0000561operators:
562
563\begin{verbatim}
564m_expr: u_expr | m_expr "*" u_expr
565 | m_expr "/" u_expr | m_expr "%" u_expr
566a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
567\end{verbatim}
568
Fred Drake5c07d9b1998-05-14 19:37:06 +0000569The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000570arguments. The arguments must either both be numbers, or one argument
Fred Drakec3b18d72000-12-07 04:54:02 +0000571must be an integer (plain or long) and the other must be a sequence.
572In the former case, the numbers are converted to a common type and
573then multiplied together. In the latter case, sequence repetition is
Fred Drakef6669171998-05-06 19:52:49 +0000574performed; a negative repetition factor yields an empty sequence.
575\index{multiplication}
576
Fred Drake5c07d9b1998-05-14 19:37:06 +0000577The \code{/} (division) operator yields the quotient of its
Fred Drakef6669171998-05-06 19:52:49 +0000578arguments. The numeric arguments are first converted to a common
579type. Plain or long integer division yields an integer of the same
580type; the result is that of mathematical division with the `floor'
581function applied to the result. Division by zero raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000582\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000583\exindex{ZeroDivisionError}
584\index{division}
585
Fred Drake5c07d9b1998-05-14 19:37:06 +0000586The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000587division of the first argument by the second. The numeric arguments
588are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000589the \exception{ZeroDivisionError} exception. The arguments may be floating
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000590point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000591\code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
592yields a result with the same sign as its second operand (or zero);
593the absolute value of the result is strictly smaller than the second
594operand.
Fred Drakef6669171998-05-06 19:52:49 +0000595\index{modulo}
596
597The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000598following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
599modulo are also connected with the built-in function \function{divmod()}:
600\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Fred Drake1ea7c751999-05-06 14:46:35 +0000601floating point and complex numbers; there similar identities hold
602approximately where \code{x/y} is replaced by \code{floor(x/y)}) or
603\code{floor(x/y) - 1} (for floats),\footnote{
604 If x is very close to an exact integer multiple of y, it's
605 possible for \code{floor(x/y)} to be one larger than
606 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
607 the latter result, in order to preserve that \code{divmod(x,y)[0]
608 * y + x \%{} y} be very close to \code{x}.
609} or \code{floor((x/y).real)} (for
610complex).
Fred Drakef6669171998-05-06 19:52:49 +0000611
Fred Drake5c07d9b1998-05-14 19:37:06 +0000612The \code{+} (addition) operator yields the sum of its arguments.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000613The arguments must either both be numbers or both sequences of the
Fred Drakef6669171998-05-06 19:52:49 +0000614same type. In the former case, the numbers are converted to a common
615type and then added together. In the latter case, the sequences are
616concatenated.
617\index{addition}
618
Fred Drake5c07d9b1998-05-14 19:37:06 +0000619The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000620arguments. The numeric arguments are first converted to a common
621type.
622\index{subtraction}
623
Fred Drake020f8c01998-07-28 19:32:59 +0000624\section{Shifting operations\label{shifting}}
Fred Drakef6669171998-05-06 19:52:49 +0000625\indexii{shifting}{operation}
626
627The shifting operations have lower priority than the arithmetic
628operations:
629
630\begin{verbatim}
631shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
632\end{verbatim}
633
634These operators accept plain or long integers as arguments. The
635arguments are converted to a common type. They shift the first
636argument to the left or right by the number of bits given by the
637second argument.
638
639A right shift by \var{n} bits is defined as division by
640\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
641multiplication with \code{pow(2,\var{n})}; for plain integers there is
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000642no overflow check so in that case the operation drops bits and flips
643the sign if the result is not less than \code{pow(2,31)} in absolute
644value. Negative shift counts raise a \exception{ValueError}
645exception.
Fred Drakef6669171998-05-06 19:52:49 +0000646\exindex{ValueError}
647
Fred Drake020f8c01998-07-28 19:32:59 +0000648\section{Binary bit-wise operations\label{bitwise}}
Fred Drakef6669171998-05-06 19:52:49 +0000649\indexiii{binary}{bit-wise}{operation}
650
651Each of the three bitwise operations has a different priority level:
652
653\begin{verbatim}
654and_expr: shift_expr | and_expr "&" shift_expr
655xor_expr: and_expr | xor_expr "^" and_expr
656or_expr: xor_expr | or_expr "|" xor_expr
657\end{verbatim}
658
Fred Drake5c07d9b1998-05-14 19:37:06 +0000659The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000660must be plain or long integers. The arguments are converted to a
661common type.
662\indexii{bit-wise}{and}
663
Fred Drake5c07d9b1998-05-14 19:37:06 +0000664The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000665arguments, which must be plain or long integers. The arguments are
666converted to a common type.
667\indexii{bit-wise}{xor}
668\indexii{exclusive}{or}
669
Fred Drake5c07d9b1998-05-14 19:37:06 +0000670The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000671arguments, which must be plain or long integers. The arguments are
672converted to a common type.
673\indexii{bit-wise}{or}
674\indexii{inclusive}{or}
675
Fred Drake020f8c01998-07-28 19:32:59 +0000676\section{Comparisons\label{comparisons}}
Fred Drakef6669171998-05-06 19:52:49 +0000677\index{comparison}
678
Fred Drake1156f622000-09-19 18:10:05 +0000679Unlike C, all comparison operations in Python have the same priority,
680which is lower than that of any arithmetic, shifting or bitwise
681operation. Also unlike C, expressions like \code{a < b < c} have the
682interpretation that is conventional in mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000683\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000684
685\begin{verbatim}
686comparison: or_expr (comp_operator or_expr)*
687comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
688\end{verbatim}
689
Fred Drake5c07d9b1998-05-14 19:37:06 +0000690Comparisons yield integer values: \code{1} for true, \code{0} for false.
Fred Drakef6669171998-05-06 19:52:49 +0000691
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000692Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
Fred Drakef6669171998-05-06 19:52:49 +0000693equivalent to \code{x < y and y <= z}, except that \code{y} is
694evaluated only once (but in both cases \code{z} is not evaluated at all
695when \code{x < y} is found to be false).
696\indexii{chaining}{comparisons}
697
698Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
699expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
700operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000701to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
Fred Drakef6669171998-05-06 19:52:49 +0000702\var{y opy z}, except that each expression is evaluated at most once.
703
704Note that \var{a opa b opb c} doesn't imply any kind of comparison
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000705between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
Fred Drakef6669171998-05-06 19:52:49 +0000706perfectly legal (though perhaps not pretty).
707
Fred Drake5c07d9b1998-05-14 19:37:06 +0000708The forms \code{<>} and \code{!=} are equivalent; for consistency with
709C, \code{!=} is preferred; where \code{!=} is mentioned below
Fred Drake1156f622000-09-19 18:10:05 +0000710\code{<>} is also accepted. The \code{<>} spelling is considered
711obsolescent.
Fred Drakef6669171998-05-06 19:52:49 +0000712
Fred Drake1156f622000-09-19 18:10:05 +0000713The operators \code{<}, \code{>}, \code{==}, \code{>=}, \code{<=}, and
714\code{!=} compare
715the values of two objects. The objects need not have the same type.
Fred Drakef6669171998-05-06 19:52:49 +0000716If both are numbers, they are coverted to a common type. Otherwise,
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000717objects of different types \emph{always} compare unequal, and are
Fred Drakef6669171998-05-06 19:52:49 +0000718ordered consistently but arbitrarily.
719
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000720(This unusual definition of comparison was used to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000721definition of operations like sorting and the \keyword{in} and
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000722\keyword{not in} operators. In the future, the comparison rules for
723objects of different types are likely to change.)
Fred Drakef6669171998-05-06 19:52:49 +0000724
725Comparison of objects of the same type depends on the type:
726
727\begin{itemize}
728
729\item
730Numbers are compared arithmetically.
731
732\item
733Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +0000734(the result of the built-in function \function{ord()}) of their
Fred Drake1156f622000-09-19 18:10:05 +0000735characters. Unicode and 8-bit strings are fully interoperable in this
736behavior.
Fred Drakef6669171998-05-06 19:52:49 +0000737
738\item
739Tuples and lists are compared lexicographically using comparison of
740corresponding items.
741
742\item
743Mappings (dictionaries) are compared through lexicographic
Fred Drakeb55ce1e1999-04-05 21:32:52 +0000744comparison of their sorted (key, value) lists.\footnote{
745This is expensive since it requires sorting the keys first,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000746but it is about the only sensible definition. An earlier version of
747Python compared dictionaries by identity only, but this caused
748surprises because people expected to be able to test a dictionary for
749emptiness by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +0000750
751\item
752Most other types compare unequal unless they are the same object;
753the choice whether one object is considered smaller or larger than
754another one is made arbitrarily but consistently within one
755execution of a program.
756
757\end{itemize}
758
Fred Drake7399b9e2000-07-11 19:43:47 +0000759The operators \keyword{in} and \keyword{not in} test for set
760membership: every type can define membership in whatever way is
761appropriate. Traditionally, this interface has been tightly bound
762the sequence interface, which is related in that presence in a sequence
763can be usefully interpreted as membership in a set.
764
765For the list, tuple 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.
768
Fred Drake1156f622000-09-19 18:10:05 +0000769For the Unicode and string types, \code{\var{x} in \var{y}} is true if
770and only if there exists an index \var{i} such that \code{\var{x} ==
771\var{y}[\var{i}]} is true. If \code{\var{x}} is not a string or
772Unicode object of length \code{1}, a \exception{TypeError} exception
773is raised.
Fred Drake7399b9e2000-07-11 19:43:47 +0000774
775For user-defined classes which define the \method{__contains__()} method,
776\code{\var{x} in \var{y}} is true if and only if
777\code{\var{y}.__contains__(\var{x})} is true.
778
779For user-defined classes which do not define \method{__contains__()} and
Fred Drake1156f622000-09-19 18:10:05 +0000780do define \method{__getitem__()}, \code{\var{x} in \var{y}} is true if
781and only if there is a non-negative integer index \var{i} such that
Fred Drake7399b9e2000-07-11 19:43:47 +0000782\code{\var{x} == \var{y}[\var{i}]}, and all lower integer indices
783do not raise \exception{IndexError} exception. (If any other exception
784is raised, it is as if \keyword{in} raised that exception).
785
786The operator \keyword{not in} is defined to have the inverse true value
787of \keyword{in}.
Fred Drakef6669171998-05-06 19:52:49 +0000788\opindex{in}
789\opindex{not in}
790\indexii{membership}{test}
791\obindex{sequence}
792
Fred Drake5c07d9b1998-05-14 19:37:06 +0000793The operators \keyword{is} and \keyword{is not} test for object identity:
794\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
795are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +0000796truth value.
797\opindex{is}
798\opindex{is not}
799\indexii{identity}{test}
800
Fred Drake020f8c01998-07-28 19:32:59 +0000801\section{Boolean operations\label{Booleans}}
Fred Drakef6669171998-05-06 19:52:49 +0000802\indexii{Boolean}{operation}
803
804Boolean operations have the lowest priority of all Python operations:
805
806\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000807expression: or_test | lambda_form
Fred Drakef6669171998-05-06 19:52:49 +0000808or_test: and_test | or_test "or" and_test
809and_test: not_test | and_test "and" not_test
810not_test: comparison | "not" not_test
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000811lambda_form: "lambda" [parameter_list]: expression
Fred Drakef6669171998-05-06 19:52:49 +0000812\end{verbatim}
813
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000814In the context of Boolean operations, and also when expressions are
Fred Drakef6669171998-05-06 19:52:49 +0000815used by control flow statements, the following values are interpreted
Fred Drake5c07d9b1998-05-14 19:37:06 +0000816as false: \code{None}, numeric zero of all types, empty sequences
Fred Drakef6669171998-05-06 19:52:49 +0000817(strings, tuples and lists), and empty mappings (dictionaries). All
818other values are interpreted as true.
819
Fred Drake5c07d9b1998-05-14 19:37:06 +0000820The operator \keyword{not} yields \code{1} if its argument is false,
821\code{0} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +0000822\opindex{not}
823
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000824The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000825\var{x} is false, its value is returned; otherwise, \var{y} is
826evaluated and the resulting value is returned.
827\opindex{and}
828
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000829The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000830\var{x} is true, its value is returned; otherwise, \var{y} is
831evaluated and the resulting value is returned.
832\opindex{or}
833
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000834(Note that neither \keyword{and} nor \keyword{or} restrict the value
Fred Drake5c07d9b1998-05-14 19:37:06 +0000835and type they return to \code{0} and \code{1}, but rather return the
836last evaluated argument.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000837This is sometimes useful, e.g., if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +0000838replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +0000839\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +0000840invent a value anyway, it does not bother to return a value of the
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000841same type as its argument, so e.g., \code{not 'foo'} yields \code{0},
Fred Drake5c07d9b1998-05-14 19:37:06 +0000842not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +0000843
844Lambda forms (lambda expressions) have the same syntactic position as
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000845expressions. They are a shorthand to create anonymous functions; the
846expression \code{lambda \var{arguments}: \var{expression}}
Fred Drakef6669171998-05-06 19:52:49 +0000847yields a function object that behaves virtually identical to one
848defined with
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000849
850\begin{verbatim}
851def name(arguments):
852 return expression
853\end{verbatim}
854
855See section \ref{function} for the syntax of parameter lists. Note
856that functions created with lambda forms cannot contain statements.
Fred Drakef6669171998-05-06 19:52:49 +0000857\label{lambda}
858\indexii{lambda}{expression}
859\indexii{lambda}{form}
860\indexii{anonmymous}{function}
861
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000862\strong{Programmer's note:} a lambda form defined inside a function
863has no access to names defined in the function's namespace. This is
864because Python has only two scopes: local and global. A common
865work-around is to use default argument values to pass selected
866variables into the lambda's namespace, e.g.:
Fred Drakef6669171998-05-06 19:52:49 +0000867
868\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000869def make_incrementor(increment):
870 return lambda x, n=increment: x+n
Fred Drakef6669171998-05-06 19:52:49 +0000871\end{verbatim}
872
Fred Drake020f8c01998-07-28 19:32:59 +0000873\section{Expression lists\label{exprlists}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000874\indexii{expression}{list}
Fred Drakef6669171998-05-06 19:52:49 +0000875
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000876\begin{verbatim}
877expression_list: expression ("," expression)* [","]
878\end{verbatim}
Fred Drakef6669171998-05-06 19:52:49 +0000879
Fred Drakec009d192000-04-25 21:09:10 +0000880An expression list containing at least one comma yields a
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000881tuple. The length of the tuple is the number of expressions in the
882list. The expressions are evaluated from left to right.
Fred Drakef6669171998-05-06 19:52:49 +0000883\obindex{tuple}
884
885The trailing comma is required only to create a single tuple (a.k.a. a
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000886\emph{singleton}); it is optional in all other cases. A single
Fred Drakec009d192000-04-25 21:09:10 +0000887expression without a trailing comma doesn't create a
888tuple, but rather yields the value of that expression.
Fred Drakef6669171998-05-06 19:52:49 +0000889(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000890\code{()}.)
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000891\indexii{trailing}{comma}
Fred Drakef6669171998-05-06 19:52:49 +0000892
Fred Draked09120b1999-04-29 16:43:42 +0000893
Fred Drake020f8c01998-07-28 19:32:59 +0000894\section{Summary\label{summary}}
Fred Drakef6669171998-05-06 19:52:49 +0000895
Fred Draked09120b1999-04-29 16:43:42 +0000896The following table summarizes the operator
897precedences\indexii{operator}{precedence} in Python, from lowest
898precedence (least binding) to highest precedence (most binding).
899Operators in the same box have the same precedence. Unless the syntax
900is explicitly given, operators are binary. Operators in the same box
901group left to right (except for comparisons, which chain from left to
902right --- see above).
Fred Drakef6669171998-05-06 19:52:49 +0000903
Fred Draked09120b1999-04-29 16:43:42 +0000904\begin{tableii}{c|l}{textrm}{Operator}{Description}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000905 \lineii{\keyword{lambda}} {Lambda expression}
906 \hline
907 \lineii{\keyword{or}} {Boolean OR}
908 \hline
909 \lineii{\keyword{and}} {Boolean AND}
910 \hline
911 \lineii{\keyword{not} \var{x}} {Boolean NOT}
912 \hline
913 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
914 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
915 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
Fred Drake9beee801998-10-21 00:44:49 +0000916 \code{<>}, \code{!=}, \code{==}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000917 {Comparisons}
918 \hline
919 \lineii{\code{|}} {Bitwise OR}
920 \hline
921 \lineii{\code{\^}} {Bitwise XOR}
922 \hline
923 \lineii{\code{\&}} {Bitwise AND}
924 \hline
925 \lineii{\code{<<}, \code{>>}} {Shifts}
926 \hline
927 \lineii{\code{+}, \code{-}}{Addition and subtraction}
928 \hline
Fred Drake9beee801998-10-21 00:44:49 +0000929 \lineii{\code{*}, \code{/}, \code{\%}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000930 {Multiplication, division, remainder}
931 \hline
932 \lineii{\code{**}} {Exponentiation}
933 \hline
934 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
935 \lineii{\code{\~\var{x}}} {Bitwise not}
936 \hline
937 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
938 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
939 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
940 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
Fred Draked09120b1999-04-29 16:43:42 +0000941 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000942 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
943 \lineii{\code{[\var{expressions}\ldots]}} {List display}
944 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
945 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
946\end{tableii}