blob: 37d1f2d0b1862690245f140d8161274c87b466b4 [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 Drake2829f1c2001-06-23 05:27:20 +000019
Fred Drake020f8c01998-07-28 19:32:59 +000020\section{Arithmetic conversions\label{conversions}}
Fred Drakef6669171998-05-06 19:52:49 +000021\indexii{arithmetic}{conversion}
22
23When a description of an arithmetic operator below uses the phrase
Guido van Rossum3a0ad601998-07-23 21:57:42 +000024``the numeric arguments are converted to a common type,'' the
25arguments are coerced using the coercion rules listed at the end of
26chapter 3. If both arguments are standard numeric types, the
27following coercions are applied:
Fred Drakef6669171998-05-06 19:52:49 +000028
29\begin{itemize}
Guido van Rossum3a0ad601998-07-23 21:57:42 +000030\item If either argument is a complex number, the other is converted
31 to complex;
32\item otherwise, if either argument is a floating point number,
Fred Drakef6669171998-05-06 19:52:49 +000033 the other is converted to floating point;
Guido van Rossum3a0ad601998-07-23 21:57:42 +000034\item otherwise, if either argument is a long integer,
Fred Drakef6669171998-05-06 19:52:49 +000035 the other is converted to long integer;
36\item otherwise, both must be plain integers and no conversion
37 is necessary.
38\end{itemize}
39
Guido van Rossum7c0240f1998-07-24 15:36:43 +000040Some additional rules apply for certain operators (e.g., a string left
Guido van Rossum3a0ad601998-07-23 21:57:42 +000041argument to the `\%' operator). Extensions can define their own
42coercions.
Fred Drake020f8c01998-07-28 19:32:59 +000043
44
45\section{Atoms\label{atoms}}
Fred Drakef6669171998-05-06 19:52:49 +000046\index{atom}
47
Guido van Rossum3a0ad601998-07-23 21:57:42 +000048Atoms are the most basic elements of expressions. The simplest atoms
49are identifiers or literals. Forms enclosed in
Fred Drakef6669171998-05-06 19:52:49 +000050reverse quotes or in parentheses, brackets or braces are also
51categorized syntactically as atoms. The syntax for atoms is:
52
53\begin{verbatim}
54atom: identifier | literal | enclosure
55enclosure: parenth_form|list_display|dict_display|string_conversion
56\end{verbatim}
57
Fred Drake2829f1c2001-06-23 05:27:20 +000058
Fred Drake020f8c01998-07-28 19:32:59 +000059\subsection{Identifiers (Names)\label{atom-identifiers}}
Fred Drakef6669171998-05-06 19:52:49 +000060\index{name}
61\index{identifier}
62
63An identifier occurring as an atom is a reference to a local, global
64or built-in name binding. If a name is assigned to anywhere in a code
65block (even in unreachable code), and is not mentioned in a
Fred Drake5c07d9b1998-05-14 19:37:06 +000066\keyword{global} statement in that code block, then it refers to a local
Fred Drakef6669171998-05-06 19:52:49 +000067name throughout that code block. When it is not assigned to anywhere
68in the block, or when it is assigned to but also explicitly listed in
Fred Drake5c07d9b1998-05-14 19:37:06 +000069a \keyword{global} statement, it refers to a global name if one exists,
Fred Drakeac79e952001-03-06 07:32:11 +000070else to a built-in name (and this binding may dynamically
71change).\footnote{The Python interpreter provides a useful set of
72 predefined built-in functions. It is not recommended to reuse
73 (hide) these names with self defined objects. See the
74 \citetitle[../lib/built-in-funcs.html]{Python Library Reference} for
75 the descriptions of built-in functions and methods.}
Fred Drakef6669171998-05-06 19:52:49 +000076\indexii{name}{binding}
77\index{code block}
78\stindex{global}
79\indexii{built-in}{name}
80\indexii{global}{name}
81
82When the name is bound to an object, evaluation of the atom yields
83that object. When a name is not bound, an attempt to evaluate it
Fred Drake5c07d9b1998-05-14 19:37:06 +000084raises a \exception{NameError} exception.
Fred Drakef6669171998-05-06 19:52:49 +000085\exindex{NameError}
86
Guido van Rossum3a0ad601998-07-23 21:57:42 +000087\strong{Private name mangling:}%
88\indexii{name}{mangling}%
89\indexii{private}{names}%
90when an identifier that textually occurs in a class definition begins
91with two or more underscore characters and does not end in two or more
Fred Drakeea81edf1998-11-25 17:51:15 +000092underscores, it is considered a \dfn{private name} of that class.
Guido van Rossum3a0ad601998-07-23 21:57:42 +000093Private names are transformed to a longer form before code is
94generated for them. The transformation inserts the class name in
95front of the name, with leading underscores removed, and a single
96underscore inserted in front of the class name. For example, the
97identifier \code{__spam} occurring in a class named \code{Ham} will be
98transformed to \code{_Ham__spam}. This transformation is independent
99of the syntactical context in which the identifier is used. If the
100transformed name is extremely long (longer than 255 characters),
101implementation defined truncation may happen. If the class name
102consists only of underscores, no transformation is done.
103
Fred Drake2829f1c2001-06-23 05:27:20 +0000104
Fred Drake020f8c01998-07-28 19:32:59 +0000105\subsection{Literals\label{atom-literals}}
Fred Drakef6669171998-05-06 19:52:49 +0000106\index{literal}
107
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000108Python supports string literals and various numeric literals:
Fred Drakef6669171998-05-06 19:52:49 +0000109
110\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000111literal: stringliteral | integer | longinteger | floatnumber | imagnumber
Fred Drakef6669171998-05-06 19:52:49 +0000112\end{verbatim}
113
114Evaluation of a literal yields an object of the given type (string,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000115integer, long integer, floating point number, complex number) with the
116given value. The value may be approximated in the case of floating
117point and imaginary (complex) literals. See section \ref{literals}
118for details.
Fred Drakef6669171998-05-06 19:52:49 +0000119
120All literals correspond to immutable data types, and hence the
121object's identity is less important than its value. Multiple
122evaluations of literals with the same value (either the same
123occurrence in the program text or a different occurrence) may obtain
124the same object or a different object with the same value.
125\indexiii{immutable}{data}{type}
Fred Drakee15956b2000-04-03 04:51:13 +0000126\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000127
Fred Drake2829f1c2001-06-23 05:27:20 +0000128
Fred Drake020f8c01998-07-28 19:32:59 +0000129\subsection{Parenthesized forms\label{parenthesized}}
Fred Drakef6669171998-05-06 19:52:49 +0000130\index{parenthesized form}
131
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000132A parenthesized form is an optional expression list enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000133parentheses:
134
135\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000136parenth_form: "(" [expression_list] ")"
Fred Drakef6669171998-05-06 19:52:49 +0000137\end{verbatim}
138
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000139A parenthesized expression list yields whatever that expression list
140yields: if the list contains at least one comma, it yields a tuple;
141otherwise, it yields the single expression that makes up the
142expression list.
Fred Drakef6669171998-05-06 19:52:49 +0000143
144An empty pair of parentheses yields an empty tuple object. Since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000145tuples are immutable, the rules for literals apply (i.e., two
146occurrences of the empty tuple may or may not yield the same object).
Fred Drakef6669171998-05-06 19:52:49 +0000147\indexii{empty}{tuple}
148
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000149Note that tuples are not formed by the parentheses, but rather by use
Fred Drakef6669171998-05-06 19:52:49 +0000150of the comma operator. The exception is the empty tuple, for which
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000151parentheses \emph{are} required --- allowing unparenthesized ``nothing''
Fred Drakef6669171998-05-06 19:52:49 +0000152in expressions would cause ambiguities and allow common typos to
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000153pass uncaught.
Fred Drakef6669171998-05-06 19:52:49 +0000154\index{comma}
155\indexii{tuple}{display}
156
Fred Drake2829f1c2001-06-23 05:27:20 +0000157
Fred Drake020f8c01998-07-28 19:32:59 +0000158\subsection{List displays\label{lists}}
Fred Drakef6669171998-05-06 19:52:49 +0000159\indexii{list}{display}
Skip Montanarob6559392000-09-11 16:31:55 +0000160\indexii{list}{comprehensions}
Fred Drakef6669171998-05-06 19:52:49 +0000161
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000162A list display is a possibly empty series of expressions enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000163square brackets:
164
165\begin{verbatim}
Fred Drakea1e214a2000-08-15 17:54:49 +0000166list_display: "[" [listmaker] "]"
Skip Montanaro46dfa5f2000-08-22 02:43:07 +0000167listmaker: expression ( list_for | ( "," expression)* [","] )
Skip Montanaro803d6e52000-08-12 18:09:51 +0000168list_iter: list_for | list_if
169list_for: "for" expression_list "in" testlist [list_iter]
170list_if: "if" test [list_iter]
Fred Drakef6669171998-05-06 19:52:49 +0000171\end{verbatim}
172
Skip Montanaro803d6e52000-08-12 18:09:51 +0000173A list display yields a new list object. Its contents are specified
174by providing either a list of expressions or a list comprehension.
Skip Montanarob6559392000-09-11 16:31:55 +0000175\indexii{list}{comprehensions}
Skip Montanaro803d6e52000-08-12 18:09:51 +0000176When a comma-separated list of expressions is supplied, its elements are
177evaluated from left to right and placed into the list object in that
178order. When a list comprehension is supplied, it consists of a
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000179single expression followed by at least one \keyword{for} clause and zero or
180more \keyword{for} or \keyword{if} clauses. In this
Skip Montanaro803d6e52000-08-12 18:09:51 +0000181case, the elements of the new list are those that would be produced
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000182by considering each of the \keyword{for} or \keyword{if} clauses a block,
183nesting from
Skip Montanaro803d6e52000-08-12 18:09:51 +0000184left to right, and evaluating the expression to produce a list element
185each time the innermost block is reached.
Fred Drakef6669171998-05-06 19:52:49 +0000186\obindex{list}
Fred Drakef6669171998-05-06 19:52:49 +0000187\indexii{empty}{list}
188
Fred Drake2829f1c2001-06-23 05:27:20 +0000189
Fred Drake020f8c01998-07-28 19:32:59 +0000190\subsection{Dictionary displays\label{dict}}
Fred Drakef6669171998-05-06 19:52:49 +0000191\indexii{dictionary}{display}
192
193A dictionary display is a possibly empty series of key/datum pairs
194enclosed in curly braces:
195\index{key}
196\index{datum}
197\index{key/datum pair}
198
199\begin{verbatim}
200dict_display: "{" [key_datum_list] "}"
201key_datum_list: key_datum ("," key_datum)* [","]
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000202key_datum: expression ":" expression
Fred Drakef6669171998-05-06 19:52:49 +0000203\end{verbatim}
204
205A dictionary display yields a new dictionary object.
206\obindex{dictionary}
207
208The key/datum pairs are evaluated from left to right to define the
209entries of the dictionary: each key object is used as a key into the
210dictionary to store the corresponding datum.
211
212Restrictions on the types of the key values are listed earlier in
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000213section \ref{types}. (To summarize,the key type should be hashable,
214which excludes all mutable objects.) Clashes between duplicate keys
215are not detected; the last datum (textually rightmost in the display)
216stored for a given key value prevails.
Fred Drakee15956b2000-04-03 04:51:13 +0000217\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000218
Fred Drake2829f1c2001-06-23 05:27:20 +0000219
Fred Drake020f8c01998-07-28 19:32:59 +0000220\subsection{String conversions\label{string-conversions}}
Fred Drakef6669171998-05-06 19:52:49 +0000221\indexii{string}{conversion}
222\indexii{reverse}{quotes}
223\indexii{backward}{quotes}
224\index{back-quotes}
225
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000226A string conversion is an expression list enclosed in reverse (a.k.a.
Fred Drakef6669171998-05-06 19:52:49 +0000227backward) quotes:
228
229\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000230string_conversion: "`" expression_list "`"
Fred Drakef6669171998-05-06 19:52:49 +0000231\end{verbatim}
232
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000233A string conversion evaluates the contained expression list and
Fred Drakef6669171998-05-06 19:52:49 +0000234converts the resulting object into a string according to rules
235specific to its type.
236
Fred Drake5c07d9b1998-05-14 19:37:06 +0000237If the object is a string, a number, \code{None}, or a tuple, list or
Fred Drakef6669171998-05-06 19:52:49 +0000238dictionary containing only objects whose type is one of these, the
239resulting string is a valid Python expression which can be passed to
Fred Drake5c07d9b1998-05-14 19:37:06 +0000240the built-in function \function{eval()} to yield an expression with the
Fred Drakef6669171998-05-06 19:52:49 +0000241same value (or an approximation, if floating point numbers are
242involved).
243
244(In particular, converting a string adds quotes around it and converts
245``funny'' characters to escape sequences that are safe to print.)
246
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000247It is illegal to attempt to convert recursive objects (e.g., lists or
Fred Drakef6669171998-05-06 19:52:49 +0000248dictionaries that contain a reference to themselves, directly or
249indirectly.)
250\obindex{recursive}
251
Fred Drake5c07d9b1998-05-14 19:37:06 +0000252The built-in function \function{repr()} performs exactly the same
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000253conversion in its argument as enclosing it in parentheses and reverse
254quotes does. The built-in function \function{str()} performs a
255similar but more user-friendly conversion.
Fred Drakef6669171998-05-06 19:52:49 +0000256\bifuncindex{repr}
257\bifuncindex{str}
258
Fred Drake2829f1c2001-06-23 05:27:20 +0000259
Fred Drake020f8c01998-07-28 19:32:59 +0000260\section{Primaries\label{primaries}}
Fred Drakef6669171998-05-06 19:52:49 +0000261\index{primary}
262
263Primaries represent the most tightly bound operations of the language.
264Their syntax is:
265
266\begin{verbatim}
267primary: atom | attributeref | subscription | slicing | call
268\end{verbatim}
269
Fred Drake2829f1c2001-06-23 05:27:20 +0000270
Fred Drake020f8c01998-07-28 19:32:59 +0000271\subsection{Attribute references\label{attribute-references}}
Fred Drakef6669171998-05-06 19:52:49 +0000272\indexii{attribute}{reference}
273
274An attribute reference is a primary followed by a period and a name:
275
276\begin{verbatim}
277attributeref: primary "." identifier
278\end{verbatim}
279
280The primary must evaluate to an object of a type that supports
Fred Drake34bafcc2001-01-14 02:57:14 +0000281attribute references, e.g., a module, list, or an instance. This
282object is then asked to produce the attribute whose name is the
283identifier. If this attribute is not available, the exception
Fred Drake5c07d9b1998-05-14 19:37:06 +0000284\exception{AttributeError}\exindex{AttributeError} is raised.
285Otherwise, the type and value of the object produced is determined by
286the object. Multiple evaluations of the same attribute reference may
287yield different objects.
Fred Drakef6669171998-05-06 19:52:49 +0000288\obindex{module}
289\obindex{list}
290
Fred Drake2829f1c2001-06-23 05:27:20 +0000291
Fred Drake020f8c01998-07-28 19:32:59 +0000292\subsection{Subscriptions\label{subscriptions}}
Fred Drakef6669171998-05-06 19:52:49 +0000293\index{subscription}
294
295A subscription selects an item of a sequence (string, tuple or list)
296or mapping (dictionary) object:
297\obindex{sequence}
298\obindex{mapping}
299\obindex{string}
300\obindex{tuple}
301\obindex{list}
302\obindex{dictionary}
303\indexii{sequence}{item}
304
305\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000306subscription: primary "[" expression_list "]"
Fred Drakef6669171998-05-06 19:52:49 +0000307\end{verbatim}
308
309The primary must evaluate to an object of a sequence or mapping type.
310
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000311If the primary is a mapping, the expression list must evaluate to an
312object whose value is one of the keys of the mapping, and the
313subscription selects the value in the mapping that corresponds to that
314key. (The expression list is a tuple except if it has exactly one
315item.)
Fred Drakef6669171998-05-06 19:52:49 +0000316
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000317If the primary is a sequence, the expression (list) must evaluate to a
318plain integer. If this value is negative, the length of the sequence
319is added to it (so that, e.g., \code{x[-1]} selects the last item of
320\code{x}.) The resulting value must be a nonnegative integer less
321than the number of items in the sequence, and the subscription selects
322the item whose index is that value (counting from zero).
Fred Drakef6669171998-05-06 19:52:49 +0000323
324A string's items are characters. A character is not a separate data
325type but a string of exactly one character.
326\index{character}
327\indexii{string}{item}
328
Fred Drake2829f1c2001-06-23 05:27:20 +0000329
Fred Drake020f8c01998-07-28 19:32:59 +0000330\subsection{Slicings\label{slicings}}
Fred Drakef6669171998-05-06 19:52:49 +0000331\index{slicing}
332\index{slice}
333
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000334A slicing selects a range of items in a sequence object (e.g., a
335string, tuple or list). Slicings may be used as expressions or as
336targets in assignment or del statements. The syntax for a slicing:
Fred Drakef6669171998-05-06 19:52:49 +0000337\obindex{sequence}
338\obindex{string}
339\obindex{tuple}
340\obindex{list}
341
342\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000343slicing: simple_slicing | extended_slicing
344simple_slicing: primary "[" short_slice "]"
345extended_slicing: primary "[" slice_list "]"
346slice_list: slice_item ("," slice_item)* [","]
347slice_item: expression | proper_slice | ellipsis
348proper_slice: short_slice | long_slice
349short_slice: [lower_bound] ":" [upper_bound]
350long_slice: short_slice ":" [stride]
351lower_bound: expression
352upper_bound: expression
353stride: expression
354ellipsis: "..."
Fred Drakef6669171998-05-06 19:52:49 +0000355\end{verbatim}
356
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000357There is ambiguity in the formal syntax here: anything that looks like
358an expression list also looks like a slice list, so any subscription
359can be interpreted as a slicing. Rather than further complicating the
360syntax, this is disambiguated by defining that in this case the
361interpretation as a subscription takes priority over the
362interpretation as a slicing (this is the case if the slice list
363contains no proper slice nor ellipses). Similarly, when the slice
364list has exactly one short slice and no trailing comma, the
365interpretation as a simple slicing takes priority over that as an
366extended slicing.\indexii{extended}{slicing}
367
368The semantics for a simple slicing are as follows. The primary must
369evaluate to a sequence object. The lower and upper bound expressions,
370if present, must evaluate to plain integers; defaults are zero and the
Fred Drakee15956b2000-04-03 04:51:13 +0000371\code{sys.maxint}, respectively. If either bound is negative, the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000372sequence's length is added to it. The slicing now selects all items
373with index \var{k} such that
Fred Drakef6669171998-05-06 19:52:49 +0000374\code{\var{i} <= \var{k} < \var{j}} where \var{i}
375and \var{j} are the specified lower and upper bounds. This may be an
376empty sequence. It is not an error if \var{i} or \var{j} lie outside the
377range of valid indexes (such items don't exist so they aren't
378selected).
379
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000380The semantics for an extended slicing are as follows. The primary
381must evaluate to a mapping object, and it is indexed with a key that
382is constructed from the slice list, as follows. If the slice list
383contains at least one comma, the key is a tuple containing the
384conversion of the slice items; otherwise, the conversion of the lone
385slice item is the key. The conversion of a slice item that is an
386expression is that expression. The conversion of an ellipsis slice
387item is the built-in \code{Ellipsis} object. The conversion of a
388proper slice is a slice object (see section \ref{types}) whose
Fred Drakeea81edf1998-11-25 17:51:15 +0000389\member{start}, \member{stop} and \member{step} attributes are the
390values of the expressions given as lower bound, upper bound and
391stride, respectively, substituting \code{None} for missing
392expressions.
Fred Drake99cd5731999-02-12 20:40:09 +0000393\withsubitem{(slice object attribute)}{\ttindex{start}
394 \ttindex{stop}\ttindex{step}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000395
Fred Drake2829f1c2001-06-23 05:27:20 +0000396
Fred Drake020f8c01998-07-28 19:32:59 +0000397\subsection{Calls\label{calls}}
Fred Drakef6669171998-05-06 19:52:49 +0000398\index{call}
399
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000400A call calls a callable object (e.g., a function) with a possibly empty
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000401series of arguments:
Fred Drakef6669171998-05-06 19:52:49 +0000402\obindex{callable}
403
404\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000405call: primary "(" [argument_list [","]] ")"
406argument_list: positional_arguments ["," keyword_arguments]
407 | keyword_arguments
408positional_arguments: expression ("," expression)*
409keyword_arguments: keyword_item ("," keyword_item)*
410keyword_item: identifier "=" expression
Fred Drakef6669171998-05-06 19:52:49 +0000411\end{verbatim}
412
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000413A trailing comma may be present after an argument list but does not
414affect the semantics.
415
Fred Drakef6669171998-05-06 19:52:49 +0000416The primary must evaluate to a callable object (user-defined
417functions, built-in functions, methods of built-in objects, class
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000418objects, methods of class instances, and certain class instances
419themselves are callable; extensions may define additional callable
420object types). All argument expressions are evaluated before the call
421is attempted. Please refer to section \ref{function} for the syntax
422of formal parameter lists.
423
424If keyword arguments are present, they are first converted to
425positional arguments, as follows. First, a list of unfilled slots is
426created for the formal parameters. If there are N positional
427arguments, they are placed in the first N slots. Next, for each
428keyword argument, the identifier is used to determine the
429corresponding slot (if the identifier is the same as the first formal
430parameter name, the first slot is used, and so on). If the slot is
431already filled, a \exception{TypeError} exception is raised.
432Otherwise, the value of the argument is placed in the slot, filling it
433(even if the expression is \code{None}, it fills the slot). When all
434arguments have been processed, the slots that are still unfilled are
435filled with the corresponding default value from the function
436definition. (Default values are calculated, once, when the function
437is defined; thus, a mutable object such as a list or dictionary used
438as default value will be shared by all calls that don't specify an
439argument value for the corresponding slot; this should usually be
440avoided.) If there are any unfilled slots for which no default value
441is specified, a \exception{TypeError} exception is raised. Otherwise,
442the list of filled slots is used as the argument list for the call.
443
444If there are more positional arguments than there are formal parameter
445slots, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000446parameter using the syntax \samp{*identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000447case, that formal parameter receives a tuple containing the excess
448positional arguments (or an empty tuple if there were no excess
449positional arguments).
450
451If any keyword argument does not correspond to a formal parameter
452name, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000453parameter using the syntax \samp{**identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000454case, that formal parameter receives a dictionary containing the
455excess keyword arguments (using the keywords as keys and the argument
456values as corresponding values), or a (new) empty dictionary if there
457were no excess keyword arguments.
458
Fred Drakeea81edf1998-11-25 17:51:15 +0000459Formal parameters using the syntax \samp{*identifier} or
460\samp{**identifier} cannot be used as positional argument slots or
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000461as keyword argument names. Formal parameters using the syntax
Fred Drakeea81edf1998-11-25 17:51:15 +0000462\samp{(sublist)} cannot be used as keyword argument names; the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000463outermost sublist corresponds to a single unnamed argument slot, and
464the argument value is assigned to the sublist using the usual tuple
465assignment rules after all other parameter processing is done.
Fred Drakef6669171998-05-06 19:52:49 +0000466
Fred Drake5c07d9b1998-05-14 19:37:06 +0000467A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000468raises an exception. How this value is computed depends on the type
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000469of the callable object.
470
471If it is---
Fred Drakef6669171998-05-06 19:52:49 +0000472
473\begin{description}
474
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000475\item[a user-defined function:] The code block for the function is
Fred Drakef6669171998-05-06 19:52:49 +0000476executed, passing it the argument list. The first thing the code
477block will do is bind the formal parameters to the arguments; this is
478described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000479\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000480function call.
481\indexii{function}{call}
482\indexiii{user-defined}{function}{call}
483\obindex{user-defined function}
484\obindex{function}
485
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000486\item[a built-in function or method:] The result is up to the
Fred Drake3d83fc32000-07-31 20:08:23 +0000487interpreter; see the \citetitle[../lib/built-in-funcs.html]{Python
488Library Reference} for the descriptions of built-in functions and
489methods.
Fred Drakef6669171998-05-06 19:52:49 +0000490\indexii{function}{call}
491\indexii{built-in function}{call}
492\indexii{method}{call}
493\indexii{built-in method}{call}
494\obindex{built-in method}
495\obindex{built-in function}
496\obindex{method}
497\obindex{function}
498
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000499\item[a class object:] A new instance of that class is returned.
Fred Drakef6669171998-05-06 19:52:49 +0000500\obindex{class}
501\indexii{class object}{call}
502
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000503\item[a class instance method:] The corresponding user-defined
Fred Drakef6669171998-05-06 19:52:49 +0000504function is called, with an argument list that is one longer than the
505argument list of the call: the instance becomes the first argument.
506\obindex{class instance}
507\obindex{instance}
Fred Drakef6669171998-05-06 19:52:49 +0000508\indexii{class instance}{call}
509
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000510\item[a class instance:] The class must define a \method{__call__()}
511method; the effect is then the same as if that method was called.
512\indexii{instance}{call}
Fred Drakeea81edf1998-11-25 17:51:15 +0000513\withsubitem{(object method)}{\ttindex{__call__()}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000514
Fred Drakef6669171998-05-06 19:52:49 +0000515\end{description}
516
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000517
Fred Drake020f8c01998-07-28 19:32:59 +0000518\section{The power operator\label{power}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000519
520The power operator binds more tightly than unary operators on its
521left; it binds less tightly than unary operators on its right. The
522syntax is:
523
524\begin{verbatim}
525power: primary ["**" u_expr]
526\end{verbatim}
527
528Thus, in an unparenthesized sequence of power and unary operators, the
529operators are evaluated from right to left (this does not constrain
530the evaluation order for the operands).
531
532The power operator has the same semantics as the built-in
533\function{pow()} function, when called with two arguments: it yields
534its left argument raised to the power of its right argument. The
535numeric arguments are first converted to a common type. The result
536type is that of the arguments after coercion; if the result is not
537expressible in that type (as in raising an integer to a negative
538power, or a negative floating point number to a broken power), a
539\exception{TypeError} exception is raised.
540
541
Fred Drakee15956b2000-04-03 04:51:13 +0000542\section{Unary arithmetic operations \label{unary}}
Fred Drakef6669171998-05-06 19:52:49 +0000543\indexiii{unary}{arithmetic}{operation}
544\indexiii{unary}{bit-wise}{operation}
545
546All unary arithmetic (and bit-wise) operations have the same priority:
547
548\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000549u_expr: power | "-" u_expr | "+" u_expr | "~" u_expr
Fred Drakef6669171998-05-06 19:52:49 +0000550\end{verbatim}
551
Fred Drake5c07d9b1998-05-14 19:37:06 +0000552The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000553numeric argument.
554\index{negation}
555\index{minus}
556
Fred Drake5c07d9b1998-05-14 19:37:06 +0000557The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000558unchanged.
559\index{plus}
560
Fred Drakee15956b2000-04-03 04:51:13 +0000561The unary \code{\~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000562of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000563\code{x} is defined as \code{-(x+1)}. It only applies to integral
564numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000565\index{inversion}
566
567In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000568a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000569\exindex{TypeError}
570
Fred Drake2829f1c2001-06-23 05:27:20 +0000571
Fred Drake020f8c01998-07-28 19:32:59 +0000572\section{Binary arithmetic operations\label{binary}}
Fred Drakef6669171998-05-06 19:52:49 +0000573\indexiii{binary}{arithmetic}{operation}
574
575The binary arithmetic operations have the conventional priority
576levels. Note that some of these operations also apply to certain
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000577non-numeric types. Apart from the power operator, there are only two
578levels, one for multiplicative operators and one for additive
Fred Drakef6669171998-05-06 19:52:49 +0000579operators:
580
581\begin{verbatim}
582m_expr: u_expr | m_expr "*" u_expr
583 | m_expr "/" u_expr | m_expr "%" u_expr
584a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
585\end{verbatim}
586
Fred Drake5c07d9b1998-05-14 19:37:06 +0000587The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000588arguments. The arguments must either both be numbers, or one argument
Fred Drakec3b18d72000-12-07 04:54:02 +0000589must be an integer (plain or long) and the other must be a sequence.
590In the former case, the numbers are converted to a common type and
591then multiplied together. In the latter case, sequence repetition is
Fred Drakef6669171998-05-06 19:52:49 +0000592performed; a negative repetition factor yields an empty sequence.
593\index{multiplication}
594
Fred Drake5c07d9b1998-05-14 19:37:06 +0000595The \code{/} (division) operator yields the quotient of its
Fred Drakef6669171998-05-06 19:52:49 +0000596arguments. The numeric arguments are first converted to a common
597type. Plain or long integer division yields an integer of the same
598type; the result is that of mathematical division with the `floor'
599function applied to the result. Division by zero raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000600\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000601\exindex{ZeroDivisionError}
602\index{division}
603
Fred Drake5c07d9b1998-05-14 19:37:06 +0000604The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000605division of the first argument by the second. The numeric arguments
606are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000607the \exception{ZeroDivisionError} exception. The arguments may be floating
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000608point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000609\code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
610yields a result with the same sign as its second operand (or zero);
611the absolute value of the result is strictly smaller than the second
612operand.
Fred Drakef6669171998-05-06 19:52:49 +0000613\index{modulo}
614
615The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000616following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
617modulo are also connected with the built-in function \function{divmod()}:
618\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Fred Drake1ea7c751999-05-06 14:46:35 +0000619floating point and complex numbers; there similar identities hold
620approximately where \code{x/y} is replaced by \code{floor(x/y)}) or
621\code{floor(x/y) - 1} (for floats),\footnote{
622 If x is very close to an exact integer multiple of y, it's
623 possible for \code{floor(x/y)} to be one larger than
624 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
625 the latter result, in order to preserve that \code{divmod(x,y)[0]
626 * y + x \%{} y} be very close to \code{x}.
627} or \code{floor((x/y).real)} (for
628complex).
Fred Drakef6669171998-05-06 19:52:49 +0000629
Fred Drake5c07d9b1998-05-14 19:37:06 +0000630The \code{+} (addition) operator yields the sum of its arguments.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000631The arguments must either both be numbers or both sequences of the
Fred Drakef6669171998-05-06 19:52:49 +0000632same type. In the former case, the numbers are converted to a common
633type and then added together. In the latter case, the sequences are
634concatenated.
635\index{addition}
636
Fred Drake5c07d9b1998-05-14 19:37:06 +0000637The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000638arguments. The numeric arguments are first converted to a common
639type.
640\index{subtraction}
641
Fred Drake2829f1c2001-06-23 05:27:20 +0000642
Fred Drake020f8c01998-07-28 19:32:59 +0000643\section{Shifting operations\label{shifting}}
Fred Drakef6669171998-05-06 19:52:49 +0000644\indexii{shifting}{operation}
645
646The shifting operations have lower priority than the arithmetic
647operations:
648
649\begin{verbatim}
650shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
651\end{verbatim}
652
653These operators accept plain or long integers as arguments. The
654arguments are converted to a common type. They shift the first
655argument to the left or right by the number of bits given by the
656second argument.
657
658A right shift by \var{n} bits is defined as division by
659\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
660multiplication with \code{pow(2,\var{n})}; for plain integers there is
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000661no overflow check so in that case the operation drops bits and flips
662the sign if the result is not less than \code{pow(2,31)} in absolute
663value. Negative shift counts raise a \exception{ValueError}
664exception.
Fred Drakef6669171998-05-06 19:52:49 +0000665\exindex{ValueError}
666
Fred Drake2829f1c2001-06-23 05:27:20 +0000667
Fred Drake020f8c01998-07-28 19:32:59 +0000668\section{Binary bit-wise operations\label{bitwise}}
Fred Drakef6669171998-05-06 19:52:49 +0000669\indexiii{binary}{bit-wise}{operation}
670
671Each of the three bitwise operations has a different priority level:
672
673\begin{verbatim}
674and_expr: shift_expr | and_expr "&" shift_expr
675xor_expr: and_expr | xor_expr "^" and_expr
676or_expr: xor_expr | or_expr "|" xor_expr
677\end{verbatim}
678
Fred Drake5c07d9b1998-05-14 19:37:06 +0000679The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000680must be plain or long integers. The arguments are converted to a
681common type.
682\indexii{bit-wise}{and}
683
Fred Drake5c07d9b1998-05-14 19:37:06 +0000684The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000685arguments, which must be plain or long integers. The arguments are
686converted to a common type.
687\indexii{bit-wise}{xor}
688\indexii{exclusive}{or}
689
Fred Drake5c07d9b1998-05-14 19:37:06 +0000690The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000691arguments, which must be plain or long integers. The arguments are
692converted to a common type.
693\indexii{bit-wise}{or}
694\indexii{inclusive}{or}
695
Fred Drake2829f1c2001-06-23 05:27:20 +0000696
Fred Drake020f8c01998-07-28 19:32:59 +0000697\section{Comparisons\label{comparisons}}
Fred Drakef6669171998-05-06 19:52:49 +0000698\index{comparison}
699
Fred Drake1156f622000-09-19 18:10:05 +0000700Unlike C, all comparison operations in Python have the same priority,
701which is lower than that of any arithmetic, shifting or bitwise
702operation. Also unlike C, expressions like \code{a < b < c} have the
703interpretation that is conventional in mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000704\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000705
706\begin{verbatim}
707comparison: or_expr (comp_operator or_expr)*
708comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
709\end{verbatim}
710
Fred Drake5c07d9b1998-05-14 19:37:06 +0000711Comparisons yield integer values: \code{1} for true, \code{0} for false.
Fred Drakef6669171998-05-06 19:52:49 +0000712
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000713Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
Fred Drakef6669171998-05-06 19:52:49 +0000714equivalent to \code{x < y and y <= z}, except that \code{y} is
715evaluated only once (but in both cases \code{z} is not evaluated at all
716when \code{x < y} is found to be false).
717\indexii{chaining}{comparisons}
718
719Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
720expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
721operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000722to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
Fred Drakef6669171998-05-06 19:52:49 +0000723\var{y opy z}, except that each expression is evaluated at most once.
724
725Note that \var{a opa b opb c} doesn't imply any kind of comparison
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000726between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
Fred Drakef6669171998-05-06 19:52:49 +0000727perfectly legal (though perhaps not pretty).
728
Fred Drake5c07d9b1998-05-14 19:37:06 +0000729The forms \code{<>} and \code{!=} are equivalent; for consistency with
730C, \code{!=} is preferred; where \code{!=} is mentioned below
Fred Drake1156f622000-09-19 18:10:05 +0000731\code{<>} is also accepted. The \code{<>} spelling is considered
732obsolescent.
Fred Drakef6669171998-05-06 19:52:49 +0000733
Fred Drake1156f622000-09-19 18:10:05 +0000734The operators \code{<}, \code{>}, \code{==}, \code{>=}, \code{<=}, and
735\code{!=} compare
736the values of two objects. The objects need not have the same type.
Fred Drakef6669171998-05-06 19:52:49 +0000737If both are numbers, they are coverted to a common type. Otherwise,
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000738objects of different types \emph{always} compare unequal, and are
Fred Drakef6669171998-05-06 19:52:49 +0000739ordered consistently but arbitrarily.
740
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000741(This unusual definition of comparison was used to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000742definition of operations like sorting and the \keyword{in} and
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000743\keyword{not in} operators. In the future, the comparison rules for
744objects of different types are likely to change.)
Fred Drakef6669171998-05-06 19:52:49 +0000745
746Comparison of objects of the same type depends on the type:
747
748\begin{itemize}
749
750\item
751Numbers are compared arithmetically.
752
753\item
754Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +0000755(the result of the built-in function \function{ord()}) of their
Fred Drake1156f622000-09-19 18:10:05 +0000756characters. Unicode and 8-bit strings are fully interoperable in this
757behavior.
Fred Drakef6669171998-05-06 19:52:49 +0000758
759\item
760Tuples and lists are compared lexicographically using comparison of
761corresponding items.
762
763\item
764Mappings (dictionaries) are compared through lexicographic
Fred Drakeb55ce1e1999-04-05 21:32:52 +0000765comparison of their sorted (key, value) lists.\footnote{
766This is expensive since it requires sorting the keys first,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000767but it is about the only sensible definition. An earlier version of
768Python compared dictionaries by identity only, but this caused
769surprises because people expected to be able to test a dictionary for
770emptiness by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +0000771
772\item
773Most other types compare unequal unless they are the same object;
774the choice whether one object is considered smaller or larger than
775another one is made arbitrarily but consistently within one
776execution of a program.
777
778\end{itemize}
779
Fred Drake7399b9e2000-07-11 19:43:47 +0000780The operators \keyword{in} and \keyword{not in} test for set
Fred Drakeac79e952001-03-06 07:32:11 +0000781membership. \code{\var{x} in \var{s}} evaluates to true if \var{x}
782is a member of the set \var{s}, and false otherwise. \code{\var{x}
783not in \var{s}} returns the negation of \code{\var{x} in \var{s}}.
784The set membership test has traditionally been bound to sequences; an
785object is a member of a set if the set is a sequence and contains an
786element equal to that object. However, it is possible for an object
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +0000787to support membership tests without being a sequence. In particular,
788dictionaries support memership testing as a nicer way of spelling
789\code{\var{key} in \var{dict}}; other mapping types may follow suit.
Fred Drake7399b9e2000-07-11 19:43:47 +0000790
Fred Drake34bafcc2001-01-14 02:57:14 +0000791For the list and tuple types, \code{\var{x} in \var{y}} is true if and
Fred Drakeac79e952001-03-06 07:32:11 +0000792only if there exists an index \var{i} such that
Fred Drake34bafcc2001-01-14 02:57:14 +0000793\code{\var{x} == \var{y}[\var{i}]} is true.
Fred Drake7399b9e2000-07-11 19:43:47 +0000794
Fred Drake1156f622000-09-19 18:10:05 +0000795For the Unicode and string types, \code{\var{x} in \var{y}} is true if
796and only if there exists an index \var{i} such that \code{\var{x} ==
797\var{y}[\var{i}]} is true. If \code{\var{x}} is not a string or
798Unicode object of length \code{1}, a \exception{TypeError} exception
799is raised.
Fred Drake7399b9e2000-07-11 19:43:47 +0000800
801For user-defined classes which define the \method{__contains__()} method,
802\code{\var{x} in \var{y}} is true if and only if
803\code{\var{y}.__contains__(\var{x})} is true.
804
805For user-defined classes which do not define \method{__contains__()} and
Fred Drake1156f622000-09-19 18:10:05 +0000806do define \method{__getitem__()}, \code{\var{x} in \var{y}} is true if
807and only if there is a non-negative integer index \var{i} such that
Fred Drake7399b9e2000-07-11 19:43:47 +0000808\code{\var{x} == \var{y}[\var{i}]}, and all lower integer indices
809do not raise \exception{IndexError} exception. (If any other exception
810is raised, it is as if \keyword{in} raised that exception).
811
812The operator \keyword{not in} is defined to have the inverse true value
813of \keyword{in}.
Fred Drakef6669171998-05-06 19:52:49 +0000814\opindex{in}
815\opindex{not in}
816\indexii{membership}{test}
817\obindex{sequence}
818
Fred Drake5c07d9b1998-05-14 19:37:06 +0000819The operators \keyword{is} and \keyword{is not} test for object identity:
820\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
821are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +0000822truth value.
823\opindex{is}
824\opindex{is not}
825\indexii{identity}{test}
826
Fred Drake2829f1c2001-06-23 05:27:20 +0000827
Fred Drake020f8c01998-07-28 19:32:59 +0000828\section{Boolean operations\label{Booleans}}
Fred Drakef6669171998-05-06 19:52:49 +0000829\indexii{Boolean}{operation}
830
831Boolean operations have the lowest priority of all Python operations:
832
833\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000834expression: or_test | lambda_form
Fred Drakef6669171998-05-06 19:52:49 +0000835or_test: and_test | or_test "or" and_test
836and_test: not_test | and_test "and" not_test
837not_test: comparison | "not" not_test
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000838lambda_form: "lambda" [parameter_list]: expression
Fred Drakef6669171998-05-06 19:52:49 +0000839\end{verbatim}
840
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000841In the context of Boolean operations, and also when expressions are
Fred Drakef6669171998-05-06 19:52:49 +0000842used by control flow statements, the following values are interpreted
Fred Drake5c07d9b1998-05-14 19:37:06 +0000843as false: \code{None}, numeric zero of all types, empty sequences
Fred Drakef6669171998-05-06 19:52:49 +0000844(strings, tuples and lists), and empty mappings (dictionaries). All
845other values are interpreted as true.
846
Fred Drake5c07d9b1998-05-14 19:37:06 +0000847The operator \keyword{not} yields \code{1} if its argument is false,
848\code{0} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +0000849\opindex{not}
850
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000851The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000852\var{x} is false, its value is returned; otherwise, \var{y} is
853evaluated and the resulting value is returned.
854\opindex{and}
855
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000856The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000857\var{x} is true, its value is returned; otherwise, \var{y} is
858evaluated and the resulting value is returned.
859\opindex{or}
860
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000861(Note that neither \keyword{and} nor \keyword{or} restrict the value
Fred Drake5c07d9b1998-05-14 19:37:06 +0000862and type they return to \code{0} and \code{1}, but rather return the
863last evaluated argument.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000864This is sometimes useful, e.g., if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +0000865replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +0000866\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +0000867invent a value anyway, it does not bother to return a value of the
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000868same type as its argument, so e.g., \code{not 'foo'} yields \code{0},
Fred Drake5c07d9b1998-05-14 19:37:06 +0000869not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +0000870
871Lambda forms (lambda expressions) have the same syntactic position as
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000872expressions. They are a shorthand to create anonymous functions; the
873expression \code{lambda \var{arguments}: \var{expression}}
Fred Drakef6669171998-05-06 19:52:49 +0000874yields a function object that behaves virtually identical to one
875defined with
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000876
877\begin{verbatim}
878def name(arguments):
879 return expression
880\end{verbatim}
881
882See section \ref{function} for the syntax of parameter lists. Note
883that functions created with lambda forms cannot contain statements.
Fred Drakef6669171998-05-06 19:52:49 +0000884\label{lambda}
885\indexii{lambda}{expression}
886\indexii{lambda}{form}
887\indexii{anonmymous}{function}
888
Fred Drake88382692001-06-05 02:17:02 +0000889\strong{Programmer's note:} Prior to Python 2.1, a lambda form defined
890inside a function has no access to names defined in the function's
891namespace. This is because Python had only two scopes: local and
892global. A common work-around was to use default argument values to
893pass selected variables into the lambda's namespace, e.g.:
Fred Drakef6669171998-05-06 19:52:49 +0000894
895\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000896def make_incrementor(increment):
897 return lambda x, n=increment: x+n
Fred Drakef6669171998-05-06 19:52:49 +0000898\end{verbatim}
899
Fred Drake88382692001-06-05 02:17:02 +0000900As of Python 2.1, nested scopes were introduced, and this work-around
901has not been necessary. Python 2.1 supports nested scopes in modules
902which include the statement \samp{from __future__ import
903nested_scopes}, and more recent versions of Python enable nested
904scopes by default. This version works starting with Python 2.1:
905
906\begin{verbatim}
907from __future__ import nested_scopes
908
909def make_incrementor(increment):
910 return lambda x: x+increment
911\end{verbatim}
912
913
Fred Drake020f8c01998-07-28 19:32:59 +0000914\section{Expression lists\label{exprlists}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000915\indexii{expression}{list}
Fred Drakef6669171998-05-06 19:52:49 +0000916
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000917\begin{verbatim}
918expression_list: expression ("," expression)* [","]
919\end{verbatim}
Fred Drakef6669171998-05-06 19:52:49 +0000920
Fred Drakec009d192000-04-25 21:09:10 +0000921An expression list containing at least one comma yields a
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000922tuple. The length of the tuple is the number of expressions in the
923list. The expressions are evaluated from left to right.
Fred Drakef6669171998-05-06 19:52:49 +0000924\obindex{tuple}
925
926The trailing comma is required only to create a single tuple (a.k.a. a
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000927\emph{singleton}); it is optional in all other cases. A single
Fred Drakec009d192000-04-25 21:09:10 +0000928expression without a trailing comma doesn't create a
929tuple, but rather yields the value of that expression.
Fred Drakef6669171998-05-06 19:52:49 +0000930(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000931\code{()}.)
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000932\indexii{trailing}{comma}
Fred Drakef6669171998-05-06 19:52:49 +0000933
Fred Draked09120b1999-04-29 16:43:42 +0000934
Fred Drake020f8c01998-07-28 19:32:59 +0000935\section{Summary\label{summary}}
Fred Drakef6669171998-05-06 19:52:49 +0000936
Fred Draked09120b1999-04-29 16:43:42 +0000937The following table summarizes the operator
938precedences\indexii{operator}{precedence} in Python, from lowest
939precedence (least binding) to highest precedence (most binding).
940Operators in the same box have the same precedence. Unless the syntax
941is explicitly given, operators are binary. Operators in the same box
942group left to right (except for comparisons, which chain from left to
Fred Drake2a222002000-12-11 22:39:24 +0000943right --- see above, and exponentiation, which groups from right to
944left).
Fred Drakef6669171998-05-06 19:52:49 +0000945
Fred Draked09120b1999-04-29 16:43:42 +0000946\begin{tableii}{c|l}{textrm}{Operator}{Description}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000947 \lineii{\keyword{lambda}} {Lambda expression}
948 \hline
949 \lineii{\keyword{or}} {Boolean OR}
950 \hline
951 \lineii{\keyword{and}} {Boolean AND}
952 \hline
953 \lineii{\keyword{not} \var{x}} {Boolean NOT}
954 \hline
955 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
956 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
957 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
Fred Drake9beee801998-10-21 00:44:49 +0000958 \code{<>}, \code{!=}, \code{==}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000959 {Comparisons}
960 \hline
961 \lineii{\code{|}} {Bitwise OR}
962 \hline
963 \lineii{\code{\^}} {Bitwise XOR}
964 \hline
965 \lineii{\code{\&}} {Bitwise AND}
966 \hline
Fred Drake24e7a292001-04-12 12:37:03 +0000967 \lineii{\code{<}\code{<}, \code{>}\code{>}} {Shifts}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000968 \hline
969 \lineii{\code{+}, \code{-}}{Addition and subtraction}
970 \hline
Fred Drake9beee801998-10-21 00:44:49 +0000971 \lineii{\code{*}, \code{/}, \code{\%}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000972 {Multiplication, division, remainder}
973 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000974 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
975 \lineii{\code{\~\var{x}}} {Bitwise not}
976 \hline
Fred Drakeb8ac0092001-05-09 16:51:49 +0000977 \lineii{\code{**}} {Exponentiation}
978 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000979 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
980 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
981 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
982 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
Fred Draked09120b1999-04-29 16:43:42 +0000983 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000984 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
985 \lineii{\code{[\var{expressions}\ldots]}} {List display}
986 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
987 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
988\end{tableii}