blob: 61aec7dee0d74ff49798d3a7cc2cdda91ca796f9 [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
Fred Drakecb4638a2001-07-06 22:49:53 +000011\begin{productionlist}[*]
12 \production{name}{\token{othername}}
13\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000014
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
Fred Drakededa9f32001-06-23 06:06:21 +000026chapter \ref{datamodel}. If both arguments are standard numeric
27types, the following 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
Fred Drakecb4638a2001-07-06 22:49:53 +000053\begin{productionlist}
54 \production{atom}
55 {\token{identifier} | \token{literal} | \token{enclosure}}
56 \production{enclosure}
Fred Drake53815882002-03-15 23:21:37 +000057 {\token{parenth_form} | \token{list_display}}
58 \productioncont{| \token{dict_display} | \token{string_conversion}}
Fred Drakecb4638a2001-07-06 22:49:53 +000059\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000060
Fred Drake2829f1c2001-06-23 05:27:20 +000061
Fred Drake020f8c01998-07-28 19:32:59 +000062\subsection{Identifiers (Names)\label{atom-identifiers}}
Fred Drakef6669171998-05-06 19:52:49 +000063\index{name}
64\index{identifier}
65
Fred Drakec0678ff2003-09-06 03:33:32 +000066An identifier occurring as an atom is a name. See
67section~\ref{naming} for documentation of naming and binding.
Fred Drakef6669171998-05-06 19:52:49 +000068
69When the name is bound to an object, evaluation of the atom yields
70that object. When a name is not bound, an attempt to evaluate it
Fred Drake5c07d9b1998-05-14 19:37:06 +000071raises a \exception{NameError} exception.
Fred Drakef6669171998-05-06 19:52:49 +000072\exindex{NameError}
73
Fred Drakec0678ff2003-09-06 03:33:32 +000074\strong{Private name mangling:}
Guido van Rossum3a0ad601998-07-23 21:57:42 +000075\indexii{name}{mangling}%
76\indexii{private}{names}%
Fred Drakec0678ff2003-09-06 03:33:32 +000077When an identifier that textually occurs in a class definition begins
Guido van Rossum3a0ad601998-07-23 21:57:42 +000078with two or more underscore characters and does not end in two or more
Fred Drakeea81edf1998-11-25 17:51:15 +000079underscores, it is considered a \dfn{private name} of that class.
Guido van Rossum3a0ad601998-07-23 21:57:42 +000080Private names are transformed to a longer form before code is
81generated for them. The transformation inserts the class name in
82front of the name, with leading underscores removed, and a single
83underscore inserted in front of the class name. For example, the
84identifier \code{__spam} occurring in a class named \code{Ham} will be
85transformed to \code{_Ham__spam}. This transformation is independent
86of the syntactical context in which the identifier is used. If the
87transformed name is extremely long (longer than 255 characters),
88implementation defined truncation may happen. If the class name
89consists only of underscores, no transformation is done.
90
Fred Drake2829f1c2001-06-23 05:27:20 +000091
Fred Drake020f8c01998-07-28 19:32:59 +000092\subsection{Literals\label{atom-literals}}
Fred Drakef6669171998-05-06 19:52:49 +000093\index{literal}
94
Guido van Rossum3a0ad601998-07-23 21:57:42 +000095Python supports string literals and various numeric literals:
Fred Drakef6669171998-05-06 19:52:49 +000096
Fred Drakecb4638a2001-07-06 22:49:53 +000097\begin{productionlist}
98 \production{literal}
Fred Drake53815882002-03-15 23:21:37 +000099 {\token{stringliteral} | \token{integer} | \token{longinteger}}
100 \productioncont{| \token{floatnumber} | \token{imagnumber}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000101\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000102
103Evaluation of a literal yields an object of the given type (string,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000104integer, long integer, floating point number, complex number) with the
105given value. The value may be approximated in the case of floating
106point and imaginary (complex) literals. See section \ref{literals}
107for details.
Fred Drakef6669171998-05-06 19:52:49 +0000108
109All literals correspond to immutable data types, and hence the
110object's identity is less important than its value. Multiple
111evaluations of literals with the same value (either the same
112occurrence in the program text or a different occurrence) may obtain
113the same object or a different object with the same value.
114\indexiii{immutable}{data}{type}
Fred Drakee15956b2000-04-03 04:51:13 +0000115\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000116
Fred Drake2829f1c2001-06-23 05:27:20 +0000117
Fred Drake020f8c01998-07-28 19:32:59 +0000118\subsection{Parenthesized forms\label{parenthesized}}
Fred Drakef6669171998-05-06 19:52:49 +0000119\index{parenthesized form}
120
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000121A parenthesized form is an optional expression list enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000122parentheses:
123
Fred Drakecb4638a2001-07-06 22:49:53 +0000124\begin{productionlist}
125 \production{parenth_form}
126 {"(" [\token{expression_list}] ")"}
127\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000128
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000129A parenthesized expression list yields whatever that expression list
130yields: if the list contains at least one comma, it yields a tuple;
131otherwise, it yields the single expression that makes up the
132expression list.
Fred Drakef6669171998-05-06 19:52:49 +0000133
134An empty pair of parentheses yields an empty tuple object. Since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000135tuples are immutable, the rules for literals apply (i.e., two
136occurrences of the empty tuple may or may not yield the same object).
Fred Drakef6669171998-05-06 19:52:49 +0000137\indexii{empty}{tuple}
138
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000139Note that tuples are not formed by the parentheses, but rather by use
Fred Drakef6669171998-05-06 19:52:49 +0000140of the comma operator. The exception is the empty tuple, for which
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000141parentheses \emph{are} required --- allowing unparenthesized ``nothing''
Fred Drakef6669171998-05-06 19:52:49 +0000142in expressions would cause ambiguities and allow common typos to
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000143pass uncaught.
Fred Drakef6669171998-05-06 19:52:49 +0000144\index{comma}
145\indexii{tuple}{display}
146
Fred Drake2829f1c2001-06-23 05:27:20 +0000147
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
Fred Drakecb4638a2001-07-06 22:49:53 +0000155\begin{productionlist}
Fred Drake25b53582003-06-27 17:12:43 +0000156 \production{test}
157 {\token{and_test} ( "or" \token{and_test} )*
158 | \token{lambda_form}}
159 \production{testlist}
160 {\token{test} ( "," \token{test} )* [ "," ]}
Fred Drakecb4638a2001-07-06 22:49:53 +0000161 \production{list_display}
162 {"[" [\token{listmaker}] "]"}
163 \production{listmaker}
164 {\token{expression} ( \token{list_for}
Neal Norwitz4efd9172003-04-10 21:51:29 +0000165 | ( "," \token{expression} )* [","] )}
Fred Drakecb4638a2001-07-06 22:49:53 +0000166 \production{list_iter}
167 {\token{list_for} | \token{list_if}}
168 \production{list_for}
169 {"for" \token{expression_list} "in" \token{testlist}
170 [\token{list_iter}]}
171 \production{list_if}
172 {"if" \token{test} [\token{list_iter}]}
173\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000174
Skip Montanaro803d6e52000-08-12 18:09:51 +0000175A list display yields a new list object. Its contents are specified
176by providing either a list of expressions or a list comprehension.
Skip Montanarob6559392000-09-11 16:31:55 +0000177\indexii{list}{comprehensions}
Skip Montanaro803d6e52000-08-12 18:09:51 +0000178When a comma-separated list of expressions is supplied, its elements are
179evaluated from left to right and placed into the list object in that
180order. When a list comprehension is supplied, it consists of a
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000181single expression followed by at least one \keyword{for} clause and zero or
Tim Peters20524db2001-10-01 20:22:45 +0000182more \keyword{for} or \keyword{if} clauses. In this
Skip Montanaro803d6e52000-08-12 18:09:51 +0000183case, the elements of the new list are those that would be produced
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000184by considering each of the \keyword{for} or \keyword{if} clauses a block,
Tim Peters20524db2001-10-01 20:22:45 +0000185nesting from
Skip Montanaro803d6e52000-08-12 18:09:51 +0000186left to right, and evaluating the expression to produce a list element
187each time the innermost block is reached.
Fred Drakef6669171998-05-06 19:52:49 +0000188\obindex{list}
Fred Drakef6669171998-05-06 19:52:49 +0000189\indexii{empty}{list}
190
Fred Drake2829f1c2001-06-23 05:27:20 +0000191
Fred Drake020f8c01998-07-28 19:32:59 +0000192\subsection{Dictionary displays\label{dict}}
Fred Drakef6669171998-05-06 19:52:49 +0000193\indexii{dictionary}{display}
194
195A dictionary display is a possibly empty series of key/datum pairs
196enclosed in curly braces:
197\index{key}
198\index{datum}
199\index{key/datum pair}
200
Fred Drakecb4638a2001-07-06 22:49:53 +0000201\begin{productionlist}
202 \production{dict_display}
Fred Drake83d14c12002-03-16 06:35:54 +0000203 {"\{" [\token{key_datum_list}] "\}"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000204 \production{key_datum_list}
205 {\token{key_datum} ("," \token{key_datum})* [","]}
206 \production{key_datum}
207 {\token{expression} ":" \token{expression}}
208\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000209
210A dictionary display yields a new dictionary object.
211\obindex{dictionary}
212
213The key/datum pairs are evaluated from left to right to define the
214entries of the dictionary: each key object is used as a key into the
215dictionary to store the corresponding datum.
216
217Restrictions on the types of the key values are listed earlier in
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000218section \ref{types}. (To summarize,the key type should be hashable,
219which excludes all mutable objects.) Clashes between duplicate keys
220are not detected; the last datum (textually rightmost in the display)
221stored for a given key value prevails.
Fred Drakee15956b2000-04-03 04:51:13 +0000222\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000223
Fred Drake2829f1c2001-06-23 05:27:20 +0000224
Fred Drake020f8c01998-07-28 19:32:59 +0000225\subsection{String conversions\label{string-conversions}}
Fred Drakef6669171998-05-06 19:52:49 +0000226\indexii{string}{conversion}
227\indexii{reverse}{quotes}
228\indexii{backward}{quotes}
229\index{back-quotes}
230
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000231A string conversion is an expression list enclosed in reverse (a.k.a.
Fred Drakef6669171998-05-06 19:52:49 +0000232backward) quotes:
233
Fred Drakecb4638a2001-07-06 22:49:53 +0000234\begin{productionlist}
235 \production{string_conversion}
236 {"`" \token{expression_list} "`"}
237\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000238
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000239A string conversion evaluates the contained expression list and
Fred Drakef6669171998-05-06 19:52:49 +0000240converts the resulting object into a string according to rules
241specific to its type.
242
Fred Drake5c07d9b1998-05-14 19:37:06 +0000243If the object is a string, a number, \code{None}, or a tuple, list or
Fred Drakef6669171998-05-06 19:52:49 +0000244dictionary containing only objects whose type is one of these, the
245resulting string is a valid Python expression which can be passed to
Fred Drake5c07d9b1998-05-14 19:37:06 +0000246the built-in function \function{eval()} to yield an expression with the
Fred Drakef6669171998-05-06 19:52:49 +0000247same value (or an approximation, if floating point numbers are
248involved).
249
250(In particular, converting a string adds quotes around it and converts
251``funny'' characters to escape sequences that are safe to print.)
252
Fred Drakece5619e2002-11-13 15:32:34 +0000253Recursive objects (for example, lists or dictionaries that contain a
254reference to themselves, directly or indirectly) use \samp{...} to
255indicate a recursive reference, and the result cannot be passed to
256\function{eval()} to get an equal value (\exception{SyntaxError} will
257be raised instead).
Fred Drakef6669171998-05-06 19:52:49 +0000258\obindex{recursive}
259
Fred Drake5c07d9b1998-05-14 19:37:06 +0000260The built-in function \function{repr()} performs exactly the same
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000261conversion in its argument as enclosing it in parentheses and reverse
262quotes does. The built-in function \function{str()} performs a
263similar but more user-friendly conversion.
Fred Drakef6669171998-05-06 19:52:49 +0000264\bifuncindex{repr}
265\bifuncindex{str}
266
Fred Drake2829f1c2001-06-23 05:27:20 +0000267
Fred Drake020f8c01998-07-28 19:32:59 +0000268\section{Primaries\label{primaries}}
Fred Drakef6669171998-05-06 19:52:49 +0000269\index{primary}
270
271Primaries represent the most tightly bound operations of the language.
272Their syntax is:
273
Fred Drakecb4638a2001-07-06 22:49:53 +0000274\begin{productionlist}
275 \production{primary}
276 {\token{atom} | \token{attributeref}
277 | \token{subscription} | \token{slicing} | \token{call}}
278\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000279
Fred Drake2829f1c2001-06-23 05:27:20 +0000280
Fred Drake020f8c01998-07-28 19:32:59 +0000281\subsection{Attribute references\label{attribute-references}}
Fred Drakef6669171998-05-06 19:52:49 +0000282\indexii{attribute}{reference}
283
284An attribute reference is a primary followed by a period and a name:
285
Fred Drakecb4638a2001-07-06 22:49:53 +0000286\begin{productionlist}
287 \production{attributeref}
288 {\token{primary} "." \token{identifier}}
289\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000290
291The primary must evaluate to an object of a type that supports
Fred Drake34bafcc2001-01-14 02:57:14 +0000292attribute references, e.g., a module, list, or an instance. This
293object is then asked to produce the attribute whose name is the
294identifier. If this attribute is not available, the exception
Fred Drake5c07d9b1998-05-14 19:37:06 +0000295\exception{AttributeError}\exindex{AttributeError} is raised.
296Otherwise, the type and value of the object produced is determined by
297the object. Multiple evaluations of the same attribute reference may
298yield different objects.
Fred Drakef6669171998-05-06 19:52:49 +0000299\obindex{module}
300\obindex{list}
301
Fred Drake2829f1c2001-06-23 05:27:20 +0000302
Fred Drake020f8c01998-07-28 19:32:59 +0000303\subsection{Subscriptions\label{subscriptions}}
Fred Drakef6669171998-05-06 19:52:49 +0000304\index{subscription}
305
306A subscription selects an item of a sequence (string, tuple or list)
307or mapping (dictionary) object:
308\obindex{sequence}
309\obindex{mapping}
310\obindex{string}
311\obindex{tuple}
312\obindex{list}
313\obindex{dictionary}
314\indexii{sequence}{item}
315
Fred Drakecb4638a2001-07-06 22:49:53 +0000316\begin{productionlist}
317 \production{subscription}
318 {\token{primary} "[" \token{expression_list} "]"}
319\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000320
321The primary must evaluate to an object of a sequence or mapping type.
322
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000323If the primary is a mapping, the expression list must evaluate to an
324object whose value is one of the keys of the mapping, and the
325subscription selects the value in the mapping that corresponds to that
326key. (The expression list is a tuple except if it has exactly one
327item.)
Fred Drakef6669171998-05-06 19:52:49 +0000328
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000329If the primary is a sequence, the expression (list) must evaluate to a
330plain integer. If this value is negative, the length of the sequence
331is added to it (so that, e.g., \code{x[-1]} selects the last item of
332\code{x}.) The resulting value must be a nonnegative integer less
333than the number of items in the sequence, and the subscription selects
334the item whose index is that value (counting from zero).
Fred Drakef6669171998-05-06 19:52:49 +0000335
336A string's items are characters. A character is not a separate data
337type but a string of exactly one character.
338\index{character}
339\indexii{string}{item}
340
Fred Drake2829f1c2001-06-23 05:27:20 +0000341
Fred Drake020f8c01998-07-28 19:32:59 +0000342\subsection{Slicings\label{slicings}}
Fred Drakef6669171998-05-06 19:52:49 +0000343\index{slicing}
344\index{slice}
345
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000346A slicing selects a range of items in a sequence object (e.g., a
347string, tuple or list). Slicings may be used as expressions or as
348targets in assignment or del statements. The syntax for a slicing:
Fred Drakef6669171998-05-06 19:52:49 +0000349\obindex{sequence}
350\obindex{string}
351\obindex{tuple}
352\obindex{list}
353
Fred Drakecb4638a2001-07-06 22:49:53 +0000354\begin{productionlist}
355 \production{slicing}
356 {\token{simple_slicing} | \token{extended_slicing}}
357 \production{simple_slicing}
358 {\token{primary} "[" \token{short_slice} "]"}
359 \production{extended_slicing}
360 {\token{primary} "[" \token{slice_list} "]" }
361 \production{slice_list}
362 {\token{slice_item} ("," \token{slice_item})* [","]}
363 \production{slice_item}
364 {\token{expression} | \token{proper_slice} | \token{ellipsis}}
365 \production{proper_slice}
366 {\token{short_slice} | \token{long_slice}}
367 \production{short_slice}
368 {[\token{lower_bound}] ":" [\token{upper_bound}]}
369 \production{long_slice}
370 {\token{short_slice} ":" [\token{stride}]}
371 \production{lower_bound}
372 {\token{expression}}
373 \production{upper_bound}
374 {\token{expression}}
375 \production{stride}
376 {\token{expression}}
377 \production{ellipsis}
378 {"..."}
379\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000380
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000381There is ambiguity in the formal syntax here: anything that looks like
382an expression list also looks like a slice list, so any subscription
383can be interpreted as a slicing. Rather than further complicating the
384syntax, this is disambiguated by defining that in this case the
385interpretation as a subscription takes priority over the
386interpretation as a slicing (this is the case if the slice list
387contains no proper slice nor ellipses). Similarly, when the slice
388list has exactly one short slice and no trailing comma, the
389interpretation as a simple slicing takes priority over that as an
390extended slicing.\indexii{extended}{slicing}
391
392The semantics for a simple slicing are as follows. The primary must
393evaluate to a sequence object. The lower and upper bound expressions,
394if present, must evaluate to plain integers; defaults are zero and the
Fred Drakee15956b2000-04-03 04:51:13 +0000395\code{sys.maxint}, respectively. If either bound is negative, the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000396sequence's length is added to it. The slicing now selects all items
397with index \var{k} such that
Fred Drakef6669171998-05-06 19:52:49 +0000398\code{\var{i} <= \var{k} < \var{j}} where \var{i}
399and \var{j} are the specified lower and upper bounds. This may be an
400empty sequence. It is not an error if \var{i} or \var{j} lie outside the
401range of valid indexes (such items don't exist so they aren't
402selected).
403
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000404The semantics for an extended slicing are as follows. The primary
405must evaluate to a mapping object, and it is indexed with a key that
406is constructed from the slice list, as follows. If the slice list
407contains at least one comma, the key is a tuple containing the
408conversion of the slice items; otherwise, the conversion of the lone
409slice item is the key. The conversion of a slice item that is an
410expression is that expression. The conversion of an ellipsis slice
411item is the built-in \code{Ellipsis} object. The conversion of a
412proper slice is a slice object (see section \ref{types}) whose
Fred Drakeea81edf1998-11-25 17:51:15 +0000413\member{start}, \member{stop} and \member{step} attributes are the
414values of the expressions given as lower bound, upper bound and
415stride, respectively, substituting \code{None} for missing
416expressions.
Fred Drake99cd5731999-02-12 20:40:09 +0000417\withsubitem{(slice object attribute)}{\ttindex{start}
418 \ttindex{stop}\ttindex{step}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000419
Fred Drake2829f1c2001-06-23 05:27:20 +0000420
Fred Drake020f8c01998-07-28 19:32:59 +0000421\subsection{Calls\label{calls}}
Fred Drakef6669171998-05-06 19:52:49 +0000422\index{call}
423
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000424A call calls a callable object (e.g., a function) with a possibly empty
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000425series of arguments:
Fred Drakef6669171998-05-06 19:52:49 +0000426\obindex{callable}
427
Fred Drakecb4638a2001-07-06 22:49:53 +0000428\begin{productionlist}
429 \production{call}
430 {\token{primary} "(" [\token{argument_list} [","]] ")"}
431 \production{argument_list}
Fred Drake74653822002-10-07 16:28:38 +0000432 {\token{positional_arguments} ["," \token{keyword_arguments}]}
433 \productioncont{ ["," "*" \token{expression}]}
434 \productioncont{ ["," "**" \token{expression}]}
435 \productioncont{| \token{keyword_arguments} ["," "*" \token{expression}]}
436 \productioncont{ ["," "**" \token{expression}]}
Fred Drake53815882002-03-15 23:21:37 +0000437 \productioncont{| "*" \token{expression} ["," "**" \token{expression}]}
438 \productioncont{| "**" \token{expression}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000439 \production{positional_arguments}
440 {\token{expression} ("," \token{expression})*}
441 \production{keyword_arguments}
442 {\token{keyword_item} ("," \token{keyword_item})*}
443 \production{keyword_item}
444 {\token{identifier} "=" \token{expression}}
445\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000446
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000447A trailing comma may be present after an argument list but does not
448affect the semantics.
449
Fred Drakef6669171998-05-06 19:52:49 +0000450The primary must evaluate to a callable object (user-defined
451functions, built-in functions, methods of built-in objects, class
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000452objects, methods of class instances, and certain class instances
453themselves are callable; extensions may define additional callable
454object types). All argument expressions are evaluated before the call
455is attempted. Please refer to section \ref{function} for the syntax
456of formal parameter lists.
457
458If keyword arguments are present, they are first converted to
459positional arguments, as follows. First, a list of unfilled slots is
460created for the formal parameters. If there are N positional
461arguments, they are placed in the first N slots. Next, for each
462keyword argument, the identifier is used to determine the
463corresponding slot (if the identifier is the same as the first formal
464parameter name, the first slot is used, and so on). If the slot is
465already filled, a \exception{TypeError} exception is raised.
466Otherwise, the value of the argument is placed in the slot, filling it
467(even if the expression is \code{None}, it fills the slot). When all
468arguments have been processed, the slots that are still unfilled are
469filled with the corresponding default value from the function
470definition. (Default values are calculated, once, when the function
471is defined; thus, a mutable object such as a list or dictionary used
472as default value will be shared by all calls that don't specify an
473argument value for the corresponding slot; this should usually be
474avoided.) If there are any unfilled slots for which no default value
475is specified, a \exception{TypeError} exception is raised. Otherwise,
476the list of filled slots is used as the argument list for the call.
477
478If there are more positional arguments than there are formal parameter
479slots, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000480parameter using the syntax \samp{*identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000481case, that formal parameter receives a tuple containing the excess
482positional arguments (or an empty tuple if there were no excess
483positional arguments).
484
485If any keyword argument does not correspond to a formal parameter
486name, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000487parameter using the syntax \samp{**identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000488case, that formal parameter receives a dictionary containing the
489excess keyword arguments (using the keywords as keys and the argument
490values as corresponding values), or a (new) empty dictionary if there
491were no excess keyword arguments.
492
Michael W. Hudson850d3982001-12-12 11:56:33 +0000493If the syntax \samp{*expression} appears in the function call,
494\samp{expression} must evaluate to a sequence. Elements from this
495sequence are treated as if they were additional positional arguments;
496if there are postional arguments \var{x1},...,\var{xN} , and
497\samp{expression} evaluates to a sequence \var{y1},...,\var{yM}, this
498is equivalent to a call with M+N positional arguments
499\var{x1},...,\var{xN},\var{y1},...,\var{yM}.
500
501A consequence of this is that although the \samp{*expression} syntax
502appears \emph{after} any keyword arguments, it is processed
Fred Drakeb062cb22001-12-14 16:57:31 +0000503\emph{before} the keyword arguments (and the
504\samp{**expression} argument, if any -- see below). So:
Michael W. Hudson850d3982001-12-12 11:56:33 +0000505
506\begin{verbatim}
507>>> def f(a, b):
508... print a, b
509...
510>>> f(b=1, *(2,))
5112 1
512>>> f(a=1, *(2,))
513Traceback (most recent call last):
514 File "<stdin>", line 1, in ?
515TypeError: f() got multiple values for keyword argument 'a'
516>>> f(1, *(2,))
5171 2
518\end{verbatim}
519
Fred Drakeb062cb22001-12-14 16:57:31 +0000520It is unusual for both keyword arguments and the
521\samp{*expression} syntax to be used in the same call, so in practice
522this confusion does not arise.
Michael W. Hudson850d3982001-12-12 11:56:33 +0000523
524If the syntax \samp{**expression} appears in the function call,
525\samp{expression} must evaluate to a (subclass of) dictionary, the
526contents of which are treated as additional keyword arguments. In the
527case of a keyword appearing in both \samp{expression} and as an
528explicit keyword argument, a \exception{TypeError} exception is
529raised.
530
Fred Drakeea81edf1998-11-25 17:51:15 +0000531Formal parameters using the syntax \samp{*identifier} or
532\samp{**identifier} cannot be used as positional argument slots or
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000533as keyword argument names. Formal parameters using the syntax
Fred Drakeea81edf1998-11-25 17:51:15 +0000534\samp{(sublist)} cannot be used as keyword argument names; the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000535outermost sublist corresponds to a single unnamed argument slot, and
536the argument value is assigned to the sublist using the usual tuple
537assignment rules after all other parameter processing is done.
Fred Drakef6669171998-05-06 19:52:49 +0000538
Fred Drake5c07d9b1998-05-14 19:37:06 +0000539A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000540raises an exception. How this value is computed depends on the type
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000541of the callable object.
542
543If it is---
Fred Drakef6669171998-05-06 19:52:49 +0000544
545\begin{description}
546
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000547\item[a user-defined function:] The code block for the function is
Fred Drakef6669171998-05-06 19:52:49 +0000548executed, passing it the argument list. The first thing the code
549block will do is bind the formal parameters to the arguments; this is
550described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000551\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000552function call.
553\indexii{function}{call}
554\indexiii{user-defined}{function}{call}
555\obindex{user-defined function}
556\obindex{function}
557
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000558\item[a built-in function or method:] The result is up to the
Fred Drake3d83fc32000-07-31 20:08:23 +0000559interpreter; see the \citetitle[../lib/built-in-funcs.html]{Python
560Library Reference} for the descriptions of built-in functions and
561methods.
Fred Drakef6669171998-05-06 19:52:49 +0000562\indexii{function}{call}
563\indexii{built-in function}{call}
564\indexii{method}{call}
565\indexii{built-in method}{call}
566\obindex{built-in method}
567\obindex{built-in function}
568\obindex{method}
569\obindex{function}
570
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000571\item[a class object:] A new instance of that class is returned.
Fred Drakef6669171998-05-06 19:52:49 +0000572\obindex{class}
573\indexii{class object}{call}
574
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000575\item[a class instance method:] The corresponding user-defined
Fred Drakef6669171998-05-06 19:52:49 +0000576function is called, with an argument list that is one longer than the
577argument list of the call: the instance becomes the first argument.
578\obindex{class instance}
579\obindex{instance}
Fred Drakef6669171998-05-06 19:52:49 +0000580\indexii{class instance}{call}
581
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000582\item[a class instance:] The class must define a \method{__call__()}
583method; the effect is then the same as if that method was called.
584\indexii{instance}{call}
Fred Drakeea81edf1998-11-25 17:51:15 +0000585\withsubitem{(object method)}{\ttindex{__call__()}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000586
Fred Drakef6669171998-05-06 19:52:49 +0000587\end{description}
588
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000589
Fred Drake020f8c01998-07-28 19:32:59 +0000590\section{The power operator\label{power}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000591
592The power operator binds more tightly than unary operators on its
593left; it binds less tightly than unary operators on its right. The
594syntax is:
595
Fred Drakecb4638a2001-07-06 22:49:53 +0000596\begin{productionlist}
597 \production{power}
598 {\token{primary} ["**" \token{u_expr}]}
599\end{productionlist}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000600
601Thus, in an unparenthesized sequence of power and unary operators, the
602operators are evaluated from right to left (this does not constrain
603the evaluation order for the operands).
604
605The power operator has the same semantics as the built-in
606\function{pow()} function, when called with two arguments: it yields
607its left argument raised to the power of its right argument. The
608numeric arguments are first converted to a common type. The result
Raymond Hettinger0da7f392002-11-08 05:30:23 +0000609type is that of the arguments after coercion.
610
611With mixed operand types, the coercion rules for binary arithmetic
612operators apply. For int and long int operands, the result has the
613same type as the operands (after coercion) unless the second argument
614is negative; in that case, all arguments are converted to float and a
615float result is delivered. For example, \code{10**2} returns \code{100},
616but \code{10**-2} returns \code{0.01}. (This last feature was added in
617Python 2.2. In Python 2.1 and before, if both arguments were of integer
618types and the second argument was negative, an exception was raised).
619
620Raising \code{0.0} to a negative power results in a
621\exception{ZeroDivisionError}. Raising a negative number to a
622fractional power results in a \exception{ValueError}.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000623
624
Fred Drakee15956b2000-04-03 04:51:13 +0000625\section{Unary arithmetic operations \label{unary}}
Fred Drakef6669171998-05-06 19:52:49 +0000626\indexiii{unary}{arithmetic}{operation}
627\indexiii{unary}{bit-wise}{operation}
628
629All unary arithmetic (and bit-wise) operations have the same priority:
630
Fred Drakecb4638a2001-07-06 22:49:53 +0000631\begin{productionlist}
632 \production{u_expr}
633 {\token{power} | "-" \token{u_expr}
Fred Drakef6eafc32002-03-18 16:47:14 +0000634 | "+" \token{u_expr} | "{\~}" \token{u_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000635\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000636
Fred Drake5c07d9b1998-05-14 19:37:06 +0000637The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000638numeric argument.
639\index{negation}
640\index{minus}
641
Fred Drake5c07d9b1998-05-14 19:37:06 +0000642The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000643unchanged.
644\index{plus}
645
Fred Drakee15956b2000-04-03 04:51:13 +0000646The unary \code{\~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000647of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000648\code{x} is defined as \code{-(x+1)}. It only applies to integral
649numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000650\index{inversion}
651
652In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000653a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000654\exindex{TypeError}
655
Fred Drake2829f1c2001-06-23 05:27:20 +0000656
Fred Drake020f8c01998-07-28 19:32:59 +0000657\section{Binary arithmetic operations\label{binary}}
Fred Drakef6669171998-05-06 19:52:49 +0000658\indexiii{binary}{arithmetic}{operation}
659
660The binary arithmetic operations have the conventional priority
661levels. Note that some of these operations also apply to certain
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000662non-numeric types. Apart from the power operator, there are only two
663levels, one for multiplicative operators and one for additive
Fred Drakef6669171998-05-06 19:52:49 +0000664operators:
665
Fred Drakecb4638a2001-07-06 22:49:53 +0000666\begin{productionlist}
667 \production{m_expr}
668 {\token{u_expr} | \token{m_expr} "*" \token{u_expr}
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000669 | \token{m_expr} "//" \token{u_expr}
Fred Drake53815882002-03-15 23:21:37 +0000670 | \token{m_expr} "/" \token{u_expr}}
671 \productioncont{| \token{m_expr} "\%" \token{u_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000672 \production{a_expr}
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000673 {\token{m_expr} | \token{a_expr} "+" \token{m_expr}
674 | \token{a_expr} "-" \token{m_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000675\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000676
Fred Drake5c07d9b1998-05-14 19:37:06 +0000677The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000678arguments. The arguments must either both be numbers, or one argument
Fred Drakec3b18d72000-12-07 04:54:02 +0000679must be an integer (plain or long) and the other must be a sequence.
680In the former case, the numbers are converted to a common type and
681then multiplied together. In the latter case, sequence repetition is
Fred Drakef6669171998-05-06 19:52:49 +0000682performed; a negative repetition factor yields an empty sequence.
683\index{multiplication}
684
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000685The \code{/} (division) and \code{//} (floor division) operators yield
686the quotient of their arguments. The numeric arguments are first
687converted to a common type. Plain or long integer division yields an
688integer of the same type; the result is that of mathematical division
689with the `floor' function applied to the result. Division by zero
690raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000691\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000692\exindex{ZeroDivisionError}
693\index{division}
694
Fred Drake5c07d9b1998-05-14 19:37:06 +0000695The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000696division of the first argument by the second. The numeric arguments
697are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000698the \exception{ZeroDivisionError} exception. The arguments may be floating
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000699point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000700\code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
701yields a result with the same sign as its second operand (or zero);
Tim Peters5b21df42002-11-24 20:23:04 +0000702the absolute value of the result is strictly smaller than the absolute
703value of the second operand\footnote{
Gustavo Niemeyerf9554122002-11-26 18:14:35 +0000704 While \code{abs(x\%y) < abs(y)} is true mathematically, for
Tim Peters5b21df42002-11-24 20:23:04 +0000705 floats it may not be true numerically due to roundoff. For
706 example, and assuming a platform on which a Python float is an
707 IEEE 754 double-precision number, in order that \code{-1e-100 \% 1e100}
708 have the same sign as \code{1e100}, the computed result is
709 \code{-1e-100 + 1e100}, which is numerically exactly equal
710 to \code{1e100}. Function \function{fmod()} in the \module{math}
711 module returns a result whose sign matches the sign of the
712 first argument instead, and so returns \code{-1e-100} in this case.
713 Which approach is more appropriate depends on the application.
714}.
Fred Drakef6669171998-05-06 19:52:49 +0000715\index{modulo}
716
717The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000718following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
719modulo are also connected with the built-in function \function{divmod()}:
720\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Raymond Hettinger6cf09f02002-05-21 18:19:49 +0000721floating point numbers; there similar identities hold
Raymond Hettingerdaa34042003-06-26 17:41:40 +0000722approximately where \code{x/y} is replaced by \code{floor(x/y)} or
Tim Peters5b21df42002-11-24 20:23:04 +0000723\code{floor(x/y) - 1}\footnote{
Fred Drake1ea7c751999-05-06 14:46:35 +0000724 If x is very close to an exact integer multiple of y, it's
725 possible for \code{floor(x/y)} to be one larger than
726 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
727 the latter result, in order to preserve that \code{divmod(x,y)[0]
728 * y + x \%{} y} be very close to \code{x}.
Raymond Hettinger6cf09f02002-05-21 18:19:49 +0000729}.
730
Raymond Hettinger463bfaf2002-10-11 21:08:02 +0000731\deprecated{2.3}{The floor division operator, the modulo operator,
732and the \function{divmod()} function are no longer defined for complex
733numbers. Instead, convert to a floating point number using the
734\function{abs()} function if appropriate.}
Fred Drakef6669171998-05-06 19:52:49 +0000735
Fred Drake5c07d9b1998-05-14 19:37:06 +0000736The \code{+} (addition) operator yields the sum of its arguments.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000737The arguments must either both be numbers or both sequences of the
Fred Drakef6669171998-05-06 19:52:49 +0000738same type. In the former case, the numbers are converted to a common
739type and then added together. In the latter case, the sequences are
740concatenated.
741\index{addition}
742
Fred Drake5c07d9b1998-05-14 19:37:06 +0000743The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000744arguments. The numeric arguments are first converted to a common
745type.
746\index{subtraction}
747
Fred Drake2829f1c2001-06-23 05:27:20 +0000748
Fred Drake020f8c01998-07-28 19:32:59 +0000749\section{Shifting operations\label{shifting}}
Fred Drakef6669171998-05-06 19:52:49 +0000750\indexii{shifting}{operation}
751
752The shifting operations have lower priority than the arithmetic
753operations:
754
Fred Drakecb4638a2001-07-06 22:49:53 +0000755\begin{productionlist}
756 \production{shift_expr}
757 {\token{a_expr}
758 | \token{shift_expr} ( "<<" | ">>" ) \token{a_expr}}
759\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000760
761These operators accept plain or long integers as arguments. The
762arguments are converted to a common type. They shift the first
763argument to the left or right by the number of bits given by the
764second argument.
765
766A right shift by \var{n} bits is defined as division by
767\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
768multiplication with \code{pow(2,\var{n})}; for plain integers there is
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000769no overflow check so in that case the operation drops bits and flips
770the sign if the result is not less than \code{pow(2,31)} in absolute
771value. Negative shift counts raise a \exception{ValueError}
772exception.
Fred Drakef6669171998-05-06 19:52:49 +0000773\exindex{ValueError}
774
Fred Drake2829f1c2001-06-23 05:27:20 +0000775
Fred Drake020f8c01998-07-28 19:32:59 +0000776\section{Binary bit-wise operations\label{bitwise}}
Fred Drakef6669171998-05-06 19:52:49 +0000777\indexiii{binary}{bit-wise}{operation}
778
779Each of the three bitwise operations has a different priority level:
780
Fred Drakecb4638a2001-07-06 22:49:53 +0000781\begin{productionlist}
782 \production{and_expr}
783 {\token{shift_expr} | \token{and_expr} "\&" \token{shift_expr}}
784 \production{xor_expr}
785 {\token{and_expr} | \token{xor_expr} "\textasciicircum" \token{and_expr}}
786 \production{or_expr}
787 {\token{xor_expr} | \token{or_expr} "|" \token{xor_expr}}
788\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000789
Fred Drake5c07d9b1998-05-14 19:37:06 +0000790The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000791must be plain or long integers. The arguments are converted to a
792common type.
793\indexii{bit-wise}{and}
794
Fred Drake5c07d9b1998-05-14 19:37:06 +0000795The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000796arguments, which must be plain or long integers. The arguments are
797converted to a common type.
798\indexii{bit-wise}{xor}
799\indexii{exclusive}{or}
800
Fred Drake5c07d9b1998-05-14 19:37:06 +0000801The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000802arguments, which must be plain or long integers. The arguments are
803converted to a common type.
804\indexii{bit-wise}{or}
805\indexii{inclusive}{or}
806
Fred Drake2829f1c2001-06-23 05:27:20 +0000807
Fred Drake020f8c01998-07-28 19:32:59 +0000808\section{Comparisons\label{comparisons}}
Fred Drakef6669171998-05-06 19:52:49 +0000809\index{comparison}
810
Fred Drake1156f622000-09-19 18:10:05 +0000811Unlike C, all comparison operations in Python have the same priority,
812which is lower than that of any arithmetic, shifting or bitwise
813operation. Also unlike C, expressions like \code{a < b < c} have the
814interpretation that is conventional in mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000815\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000816
Fred Drakecb4638a2001-07-06 22:49:53 +0000817\begin{productionlist}
818 \production{comparison}
819 {\token{or_expr} ( \token{comp_operator} \token{or_expr} )*}
820 \production{comp_operator}
Fred Drake53815882002-03-15 23:21:37 +0000821 {"<" | ">" | "==" | ">=" | "<=" | "<>" | "!="}
822 \productioncont{| "is" ["not"] | ["not"] "in"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000823\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000824
Raymond Hettingerb268f032003-06-06 02:52:14 +0000825Comparisons yield boolean values: \code{True} or \code{False}.
Fred Drakef6669171998-05-06 19:52:49 +0000826
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000827Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
Fred Drakef6669171998-05-06 19:52:49 +0000828equivalent to \code{x < y and y <= z}, except that \code{y} is
829evaluated only once (but in both cases \code{z} is not evaluated at all
830when \code{x < y} is found to be false).
831\indexii{chaining}{comparisons}
832
833Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
834expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
835operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000836to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
Fred Drakef6669171998-05-06 19:52:49 +0000837\var{y opy z}, except that each expression is evaluated at most once.
838
839Note that \var{a opa b opb c} doesn't imply any kind of comparison
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000840between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
Fred Drakef6669171998-05-06 19:52:49 +0000841perfectly legal (though perhaps not pretty).
842
Fred Drake5c07d9b1998-05-14 19:37:06 +0000843The forms \code{<>} and \code{!=} are equivalent; for consistency with
844C, \code{!=} is preferred; where \code{!=} is mentioned below
Fred Drake1156f622000-09-19 18:10:05 +0000845\code{<>} is also accepted. The \code{<>} spelling is considered
846obsolescent.
Fred Drakef6669171998-05-06 19:52:49 +0000847
Fred Drake1156f622000-09-19 18:10:05 +0000848The operators \code{<}, \code{>}, \code{==}, \code{>=}, \code{<=}, and
849\code{!=} compare
850the values of two objects. The objects need not have the same type.
Fred Drakefd867712002-04-09 14:39:10 +0000851If both are numbers, they are converted to a common type. Otherwise,
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000852objects of different types \emph{always} compare unequal, and are
Fred Drakef6669171998-05-06 19:52:49 +0000853ordered consistently but arbitrarily.
854
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000855(This unusual definition of comparison was used to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000856definition of operations like sorting and the \keyword{in} and
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000857\keyword{not in} operators. In the future, the comparison rules for
858objects of different types are likely to change.)
Fred Drakef6669171998-05-06 19:52:49 +0000859
860Comparison of objects of the same type depends on the type:
861
862\begin{itemize}
863
864\item
865Numbers are compared arithmetically.
866
867\item
868Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +0000869(the result of the built-in function \function{ord()}) of their
Fred Drake1156f622000-09-19 18:10:05 +0000870characters. Unicode and 8-bit strings are fully interoperable in this
871behavior.
Fred Drakef6669171998-05-06 19:52:49 +0000872
873\item
874Tuples and lists are compared lexicographically using comparison of
Raymond Hettingerdaa34042003-06-26 17:41:40 +0000875corresponding elements. This means that to compare equal, each
876element must compare equal and the two sequences must be of the same
877type and have the same length.
878
879If not equal, the sequences are ordered the same as their first
880differing elements. For example, \code{cmp([1,2,x], [1,2,y])} returns
881the same as \code{cmp(x,y)}. If the corresponding element does not
882exist, the shorter sequence is ordered first (for example,
883\code{[1,2] < [1,2,3]}).
Fred Drakef6669171998-05-06 19:52:49 +0000884
885\item
Tim Peters20524db2001-10-01 20:22:45 +0000886Mappings (dictionaries) compare equal if and only if their sorted
887(key, value) lists compare equal.\footnote{The implementation computes
888 this efficiently, without constructing lists or sorting.}
889Outcomes other than equality are resolved consistently, but are not
Tim Peters1350c072001-10-01 20:25:26 +0000890otherwise defined.\footnote{Earlier versions of Python used
Tim Peters20524db2001-10-01 20:22:45 +0000891 lexicographic comparison of the sorted (key, value) lists, but this
892 was very expensive for the common case of comparing for equality. An
893 even earlier version of Python compared dictionaries by identity only,
894 but this caused surprises because people expected to be able to test
895 a dictionary for emptiness by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +0000896
897\item
898Most other types compare unequal unless they are the same object;
899the choice whether one object is considered smaller or larger than
900another one is made arbitrarily but consistently within one
901execution of a program.
902
903\end{itemize}
904
Fred Drake7399b9e2000-07-11 19:43:47 +0000905The operators \keyword{in} and \keyword{not in} test for set
Fred Drakeac79e952001-03-06 07:32:11 +0000906membership. \code{\var{x} in \var{s}} evaluates to true if \var{x}
907is a member of the set \var{s}, and false otherwise. \code{\var{x}
908not in \var{s}} returns the negation of \code{\var{x} in \var{s}}.
909The set membership test has traditionally been bound to sequences; an
910object is a member of a set if the set is a sequence and contains an
911element equal to that object. However, it is possible for an object
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +0000912to support membership tests without being a sequence. In particular,
913dictionaries support memership testing as a nicer way of spelling
914\code{\var{key} in \var{dict}}; other mapping types may follow suit.
Fred Drake7399b9e2000-07-11 19:43:47 +0000915
Fred Drake34bafcc2001-01-14 02:57:14 +0000916For the list and tuple types, \code{\var{x} in \var{y}} is true if and
Fred Drakeac79e952001-03-06 07:32:11 +0000917only if there exists an index \var{i} such that
Fred Drake34bafcc2001-01-14 02:57:14 +0000918\code{\var{x} == \var{y}[\var{i}]} is true.
Fred Drake7399b9e2000-07-11 19:43:47 +0000919
Fred Drake1156f622000-09-19 18:10:05 +0000920For the Unicode and string types, \code{\var{x} in \var{y}} is true if
Raymond Hettingerd0cda1d2003-06-26 19:32:10 +0000921and only if \var{x} is a substring of \var{y}. An equivalent test is
922\code{y.find(x) != -1}. Note, \var{x} and \var{y} need not be the
923same type; consequently, \code{u'ab' in 'abc'} will return \code{True}.
924Empty strings are always considered to be a substring of any other string,
925so \code{"" in "abc"} will return \code{True}.
926\versionchanged[Previously, \var{x} was required to be a string of
927length \code{1}]{2.3}
Fred Drake7399b9e2000-07-11 19:43:47 +0000928
929For user-defined classes which define the \method{__contains__()} method,
930\code{\var{x} in \var{y}} is true if and only if
931\code{\var{y}.__contains__(\var{x})} is true.
932
933For user-defined classes which do not define \method{__contains__()} and
Fred Drake1156f622000-09-19 18:10:05 +0000934do define \method{__getitem__()}, \code{\var{x} in \var{y}} is true if
935and only if there is a non-negative integer index \var{i} such that
Fred Drake7399b9e2000-07-11 19:43:47 +0000936\code{\var{x} == \var{y}[\var{i}]}, and all lower integer indices
937do not raise \exception{IndexError} exception. (If any other exception
938is raised, it is as if \keyword{in} raised that exception).
939
940The operator \keyword{not in} is defined to have the inverse true value
941of \keyword{in}.
Fred Drakef6669171998-05-06 19:52:49 +0000942\opindex{in}
943\opindex{not in}
944\indexii{membership}{test}
945\obindex{sequence}
946
Fred Drake5c07d9b1998-05-14 19:37:06 +0000947The operators \keyword{is} and \keyword{is not} test for object identity:
948\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
949are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +0000950truth value.
951\opindex{is}
952\opindex{is not}
953\indexii{identity}{test}
954
Fred Drake2829f1c2001-06-23 05:27:20 +0000955
Fred Drake020f8c01998-07-28 19:32:59 +0000956\section{Boolean operations\label{Booleans}}
Fred Drakef6669171998-05-06 19:52:49 +0000957\indexii{Boolean}{operation}
958
959Boolean operations have the lowest priority of all Python operations:
960
Fred Drakecb4638a2001-07-06 22:49:53 +0000961\begin{productionlist}
962 \production{expression}
963 {\token{or_test} | \token{lambda_form}}
964 \production{or_test}
965 {\token{and_test} | \token{or_test} "or" \token{and_test}}
966 \production{and_test}
967 {\token{not_test} | \token{and_test} "and" \token{not_test}}
968 \production{not_test}
969 {\token{comparison} | "not" \token{not_test}}
970 \production{lambda_form}
971 {"lambda" [\token{parameter_list}]: \token{expression}}
972\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000973
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000974In the context of Boolean operations, and also when expressions are
Fred Drakef6669171998-05-06 19:52:49 +0000975used by control flow statements, the following values are interpreted
Fred Drake5c07d9b1998-05-14 19:37:06 +0000976as false: \code{None}, numeric zero of all types, empty sequences
Fred Drakef6669171998-05-06 19:52:49 +0000977(strings, tuples and lists), and empty mappings (dictionaries). All
978other values are interpreted as true.
979
Fred Drake5c07d9b1998-05-14 19:37:06 +0000980The operator \keyword{not} yields \code{1} if its argument is false,
981\code{0} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +0000982\opindex{not}
983
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000984The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000985\var{x} is false, its value is returned; otherwise, \var{y} is
986evaluated and the resulting value is returned.
987\opindex{and}
988
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000989The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000990\var{x} is true, its value is returned; otherwise, \var{y} is
991evaluated and the resulting value is returned.
992\opindex{or}
993
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000994(Note that neither \keyword{and} nor \keyword{or} restrict the value
Fred Drake5c07d9b1998-05-14 19:37:06 +0000995and type they return to \code{0} and \code{1}, but rather return the
996last evaluated argument.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000997This is sometimes useful, e.g., if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +0000998replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +0000999\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +00001000invent a value anyway, it does not bother to return a value of the
Guido van Rossum7c0240f1998-07-24 15:36:43 +00001001same type as its argument, so e.g., \code{not 'foo'} yields \code{0},
Fred Drake5c07d9b1998-05-14 19:37:06 +00001002not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +00001003
Jeremy Hylton2225add2002-04-01 21:05:21 +00001004\section{Lambdas\label{lambdas}}
1005\indexii{lambda}{expression}
1006\indexii{lambda}{form}
Martin v. Löwis95cf84a2003-10-19 07:32:24 +00001007\indexii{anonymous}{function}
Jeremy Hylton2225add2002-04-01 21:05:21 +00001008
Fred Drakef6669171998-05-06 19:52:49 +00001009Lambda forms (lambda expressions) have the same syntactic position as
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001010expressions. They are a shorthand to create anonymous functions; the
1011expression \code{lambda \var{arguments}: \var{expression}}
Jeremy Hylton2225add2002-04-01 21:05:21 +00001012yields a function object. The unnamed object behaves like a function
Raymond Hettinger7fd9ced2002-06-25 04:04:14 +00001013object defined with
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001014
1015\begin{verbatim}
1016def name(arguments):
1017 return expression
1018\end{verbatim}
1019
1020See section \ref{function} for the syntax of parameter lists. Note
1021that functions created with lambda forms cannot contain statements.
Fred Drakef6669171998-05-06 19:52:49 +00001022\label{lambda}
Fred Drake88382692001-06-05 02:17:02 +00001023
Fred Drake020f8c01998-07-28 19:32:59 +00001024\section{Expression lists\label{exprlists}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001025\indexii{expression}{list}
Fred Drakef6669171998-05-06 19:52:49 +00001026
Fred Drakecb4638a2001-07-06 22:49:53 +00001027\begin{productionlist}
1028 \production{expression_list}
1029 {\token{expression} ( "," \token{expression} )* [","]}
1030\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +00001031
Fred Drakec009d192000-04-25 21:09:10 +00001032An expression list containing at least one comma yields a
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001033tuple. The length of the tuple is the number of expressions in the
1034list. The expressions are evaluated from left to right.
Fred Drakef6669171998-05-06 19:52:49 +00001035\obindex{tuple}
1036
1037The trailing comma is required only to create a single tuple (a.k.a. a
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001038\emph{singleton}); it is optional in all other cases. A single
Fred Drakec009d192000-04-25 21:09:10 +00001039expression without a trailing comma doesn't create a
1040tuple, but rather yields the value of that expression.
Fred Drakef6669171998-05-06 19:52:49 +00001041(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +00001042\code{()}.)
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001043\indexii{trailing}{comma}
Fred Drakef6669171998-05-06 19:52:49 +00001044
Gustavo Niemeyer78429a62002-12-16 13:54:02 +00001045\section{Evaluation order\label{evalorder}}
1046\indexii{evaluation}{order}
1047
1048Python evaluates expressions from left to right. Notice that while
1049evaluating an assignment, the right-hand side is evaluated before
1050the left-hand side.
1051
1052In the following lines, expressions will be evaluated in the
1053arithmetic order of their suffixes:
1054
1055\begin{verbatim}
1056expr1, expr2, expr3, expr4
1057(expr1, expr2, expr3, expr4)
1058{expr1: expr2, expr3: expr4}
1059expr1 + expr2 * (expr3 - expr4)
1060func(expr1, expr2, *expr3, **expr4)
1061expr3, expr4 = expr1, expr2
1062\end{verbatim}
Fred Draked09120b1999-04-29 16:43:42 +00001063
Fred Drake020f8c01998-07-28 19:32:59 +00001064\section{Summary\label{summary}}
Fred Drakef6669171998-05-06 19:52:49 +00001065
Fred Draked09120b1999-04-29 16:43:42 +00001066The following table summarizes the operator
1067precedences\indexii{operator}{precedence} in Python, from lowest
1068precedence (least binding) to highest precedence (most binding).
1069Operators in the same box have the same precedence. Unless the syntax
1070is explicitly given, operators are binary. Operators in the same box
1071group left to right (except for comparisons, which chain from left to
Fred Drake2a222002000-12-11 22:39:24 +00001072right --- see above, and exponentiation, which groups from right to
1073left).
Fred Drakef6669171998-05-06 19:52:49 +00001074
Fred Draked09120b1999-04-29 16:43:42 +00001075\begin{tableii}{c|l}{textrm}{Operator}{Description}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001076 \lineii{\keyword{lambda}} {Lambda expression}
1077 \hline
1078 \lineii{\keyword{or}} {Boolean OR}
1079 \hline
1080 \lineii{\keyword{and}} {Boolean AND}
1081 \hline
1082 \lineii{\keyword{not} \var{x}} {Boolean NOT}
1083 \hline
1084 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
1085 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
1086 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
Fred Drake9beee801998-10-21 00:44:49 +00001087 \code{<>}, \code{!=}, \code{==}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001088 {Comparisons}
1089 \hline
1090 \lineii{\code{|}} {Bitwise OR}
1091 \hline
1092 \lineii{\code{\^}} {Bitwise XOR}
1093 \hline
1094 \lineii{\code{\&}} {Bitwise AND}
1095 \hline
Fred Drake24e7a292001-04-12 12:37:03 +00001096 \lineii{\code{<}\code{<}, \code{>}\code{>}} {Shifts}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001097 \hline
1098 \lineii{\code{+}, \code{-}}{Addition and subtraction}
1099 \hline
Fred Drake9beee801998-10-21 00:44:49 +00001100 \lineii{\code{*}, \code{/}, \code{\%}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001101 {Multiplication, division, remainder}
1102 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001103 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
1104 \lineii{\code{\~\var{x}}} {Bitwise not}
1105 \hline
Fred Drakeb8ac0092001-05-09 16:51:49 +00001106 \lineii{\code{**}} {Exponentiation}
1107 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001108 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
1109 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
1110 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
1111 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
Fred Draked09120b1999-04-29 16:43:42 +00001112 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001113 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
1114 \lineii{\code{[\var{expressions}\ldots]}} {List display}
1115 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
1116 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
1117\end{tableii}