blob: 093192026cdd12e0c5bba1542edce52b3a0a91b7 [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
Andrew M. Kuchlingcbd81552004-08-07 19:16:32 +0000187each time the innermost block is reached\footnote{In Python 2.3, a
188list comprehension "leaks" the control variables of each
189\samp{for} it contains into the containing scope. However, this
190behavior is deprecated, and relying on it will not work once this
191bug is fixed in a future release}.
Fred Drakef6669171998-05-06 19:52:49 +0000192\obindex{list}
Fred Drakef6669171998-05-06 19:52:49 +0000193\indexii{empty}{list}
194
Fred Drake2829f1c2001-06-23 05:27:20 +0000195
Fred Drake020f8c01998-07-28 19:32:59 +0000196\subsection{Dictionary displays\label{dict}}
Fred Drakef6669171998-05-06 19:52:49 +0000197\indexii{dictionary}{display}
198
199A dictionary display is a possibly empty series of key/datum pairs
200enclosed in curly braces:
201\index{key}
202\index{datum}
203\index{key/datum pair}
204
Fred Drakecb4638a2001-07-06 22:49:53 +0000205\begin{productionlist}
206 \production{dict_display}
Fred Drake83d14c12002-03-16 06:35:54 +0000207 {"\{" [\token{key_datum_list}] "\}"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000208 \production{key_datum_list}
209 {\token{key_datum} ("," \token{key_datum})* [","]}
210 \production{key_datum}
211 {\token{expression} ":" \token{expression}}
212\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000213
214A dictionary display yields a new dictionary object.
215\obindex{dictionary}
216
217The key/datum pairs are evaluated from left to right to define the
218entries of the dictionary: each key object is used as a key into the
219dictionary to store the corresponding datum.
220
221Restrictions on the types of the key values are listed earlier in
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000222section \ref{types}. (To summarize,the key type should be hashable,
223which excludes all mutable objects.) Clashes between duplicate keys
224are not detected; the last datum (textually rightmost in the display)
225stored for a given key value prevails.
Fred Drakee15956b2000-04-03 04:51:13 +0000226\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000227
Fred Drake2829f1c2001-06-23 05:27:20 +0000228
Fred Drake020f8c01998-07-28 19:32:59 +0000229\subsection{String conversions\label{string-conversions}}
Fred Drakef6669171998-05-06 19:52:49 +0000230\indexii{string}{conversion}
231\indexii{reverse}{quotes}
232\indexii{backward}{quotes}
233\index{back-quotes}
234
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000235A string conversion is an expression list enclosed in reverse (a.k.a.
Fred Drakef6669171998-05-06 19:52:49 +0000236backward) quotes:
237
Fred Drakecb4638a2001-07-06 22:49:53 +0000238\begin{productionlist}
239 \production{string_conversion}
240 {"`" \token{expression_list} "`"}
241\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000242
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000243A string conversion evaluates the contained expression list and
Fred Drakef6669171998-05-06 19:52:49 +0000244converts the resulting object into a string according to rules
245specific to its type.
246
Fred Drake5c07d9b1998-05-14 19:37:06 +0000247If the object is a string, a number, \code{None}, or a tuple, list or
Fred Drakef6669171998-05-06 19:52:49 +0000248dictionary containing only objects whose type is one of these, the
249resulting string is a valid Python expression which can be passed to
Fred Drake5c07d9b1998-05-14 19:37:06 +0000250the built-in function \function{eval()} to yield an expression with the
Fred Drakef6669171998-05-06 19:52:49 +0000251same value (or an approximation, if floating point numbers are
252involved).
253
254(In particular, converting a string adds quotes around it and converts
255``funny'' characters to escape sequences that are safe to print.)
256
Fred Drakece5619e2002-11-13 15:32:34 +0000257Recursive objects (for example, lists or dictionaries that contain a
258reference to themselves, directly or indirectly) use \samp{...} to
259indicate a recursive reference, and the result cannot be passed to
260\function{eval()} to get an equal value (\exception{SyntaxError} will
261be raised instead).
Fred Drakef6669171998-05-06 19:52:49 +0000262\obindex{recursive}
263
Fred Drake5c07d9b1998-05-14 19:37:06 +0000264The built-in function \function{repr()} performs exactly the same
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000265conversion in its argument as enclosing it in parentheses and reverse
266quotes does. The built-in function \function{str()} performs a
267similar but more user-friendly conversion.
Fred Drakef6669171998-05-06 19:52:49 +0000268\bifuncindex{repr}
269\bifuncindex{str}
270
Fred Drake2829f1c2001-06-23 05:27:20 +0000271
Fred Drake020f8c01998-07-28 19:32:59 +0000272\section{Primaries\label{primaries}}
Fred Drakef6669171998-05-06 19:52:49 +0000273\index{primary}
274
275Primaries represent the most tightly bound operations of the language.
276Their syntax is:
277
Fred Drakecb4638a2001-07-06 22:49:53 +0000278\begin{productionlist}
279 \production{primary}
280 {\token{atom} | \token{attributeref}
281 | \token{subscription} | \token{slicing} | \token{call}}
282\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000283
Fred Drake2829f1c2001-06-23 05:27:20 +0000284
Fred Drake020f8c01998-07-28 19:32:59 +0000285\subsection{Attribute references\label{attribute-references}}
Fred Drakef6669171998-05-06 19:52:49 +0000286\indexii{attribute}{reference}
287
288An attribute reference is a primary followed by a period and a name:
289
Fred Drakecb4638a2001-07-06 22:49:53 +0000290\begin{productionlist}
291 \production{attributeref}
292 {\token{primary} "." \token{identifier}}
293\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000294
295The primary must evaluate to an object of a type that supports
Fred Drake34bafcc2001-01-14 02:57:14 +0000296attribute references, e.g., a module, list, or an instance. This
297object is then asked to produce the attribute whose name is the
298identifier. If this attribute is not available, the exception
Fred Drake5c07d9b1998-05-14 19:37:06 +0000299\exception{AttributeError}\exindex{AttributeError} is raised.
300Otherwise, the type and value of the object produced is determined by
301the object. Multiple evaluations of the same attribute reference may
302yield different objects.
Fred Drakef6669171998-05-06 19:52:49 +0000303\obindex{module}
304\obindex{list}
305
Fred Drake2829f1c2001-06-23 05:27:20 +0000306
Fred Drake020f8c01998-07-28 19:32:59 +0000307\subsection{Subscriptions\label{subscriptions}}
Fred Drakef6669171998-05-06 19:52:49 +0000308\index{subscription}
309
310A subscription selects an item of a sequence (string, tuple or list)
311or mapping (dictionary) object:
312\obindex{sequence}
313\obindex{mapping}
314\obindex{string}
315\obindex{tuple}
316\obindex{list}
317\obindex{dictionary}
318\indexii{sequence}{item}
319
Fred Drakecb4638a2001-07-06 22:49:53 +0000320\begin{productionlist}
321 \production{subscription}
322 {\token{primary} "[" \token{expression_list} "]"}
323\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000324
325The primary must evaluate to an object of a sequence or mapping type.
326
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000327If the primary is a mapping, the expression list must evaluate to an
328object whose value is one of the keys of the mapping, and the
329subscription selects the value in the mapping that corresponds to that
330key. (The expression list is a tuple except if it has exactly one
331item.)
Fred Drakef6669171998-05-06 19:52:49 +0000332
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000333If the primary is a sequence, the expression (list) must evaluate to a
334plain integer. If this value is negative, the length of the sequence
335is added to it (so that, e.g., \code{x[-1]} selects the last item of
336\code{x}.) The resulting value must be a nonnegative integer less
337than the number of items in the sequence, and the subscription selects
338the item whose index is that value (counting from zero).
Fred Drakef6669171998-05-06 19:52:49 +0000339
340A string's items are characters. A character is not a separate data
341type but a string of exactly one character.
342\index{character}
343\indexii{string}{item}
344
Fred Drake2829f1c2001-06-23 05:27:20 +0000345
Fred Drake020f8c01998-07-28 19:32:59 +0000346\subsection{Slicings\label{slicings}}
Fred Drakef6669171998-05-06 19:52:49 +0000347\index{slicing}
348\index{slice}
349
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000350A slicing selects a range of items in a sequence object (e.g., a
351string, tuple or list). Slicings may be used as expressions or as
352targets in assignment or del statements. The syntax for a slicing:
Fred Drakef6669171998-05-06 19:52:49 +0000353\obindex{sequence}
354\obindex{string}
355\obindex{tuple}
356\obindex{list}
357
Fred Drakecb4638a2001-07-06 22:49:53 +0000358\begin{productionlist}
359 \production{slicing}
360 {\token{simple_slicing} | \token{extended_slicing}}
361 \production{simple_slicing}
362 {\token{primary} "[" \token{short_slice} "]"}
363 \production{extended_slicing}
364 {\token{primary} "[" \token{slice_list} "]" }
365 \production{slice_list}
366 {\token{slice_item} ("," \token{slice_item})* [","]}
367 \production{slice_item}
368 {\token{expression} | \token{proper_slice} | \token{ellipsis}}
369 \production{proper_slice}
370 {\token{short_slice} | \token{long_slice}}
371 \production{short_slice}
372 {[\token{lower_bound}] ":" [\token{upper_bound}]}
373 \production{long_slice}
374 {\token{short_slice} ":" [\token{stride}]}
375 \production{lower_bound}
376 {\token{expression}}
377 \production{upper_bound}
378 {\token{expression}}
379 \production{stride}
380 {\token{expression}}
381 \production{ellipsis}
382 {"..."}
383\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000384
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000385There is ambiguity in the formal syntax here: anything that looks like
386an expression list also looks like a slice list, so any subscription
387can be interpreted as a slicing. Rather than further complicating the
388syntax, this is disambiguated by defining that in this case the
389interpretation as a subscription takes priority over the
390interpretation as a slicing (this is the case if the slice list
391contains no proper slice nor ellipses). Similarly, when the slice
392list has exactly one short slice and no trailing comma, the
393interpretation as a simple slicing takes priority over that as an
394extended slicing.\indexii{extended}{slicing}
395
396The semantics for a simple slicing are as follows. The primary must
397evaluate to a sequence object. The lower and upper bound expressions,
398if present, must evaluate to plain integers; defaults are zero and the
Fred Drakee15956b2000-04-03 04:51:13 +0000399\code{sys.maxint}, respectively. If either bound is negative, the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000400sequence's length is added to it. The slicing now selects all items
401with index \var{k} such that
Fred Drakef6669171998-05-06 19:52:49 +0000402\code{\var{i} <= \var{k} < \var{j}} where \var{i}
403and \var{j} are the specified lower and upper bounds. This may be an
404empty sequence. It is not an error if \var{i} or \var{j} lie outside the
405range of valid indexes (such items don't exist so they aren't
406selected).
407
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000408The semantics for an extended slicing are as follows. The primary
409must evaluate to a mapping object, and it is indexed with a key that
410is constructed from the slice list, as follows. If the slice list
411contains at least one comma, the key is a tuple containing the
412conversion of the slice items; otherwise, the conversion of the lone
413slice item is the key. The conversion of a slice item that is an
414expression is that expression. The conversion of an ellipsis slice
415item is the built-in \code{Ellipsis} object. The conversion of a
416proper slice is a slice object (see section \ref{types}) whose
Fred Drakeea81edf1998-11-25 17:51:15 +0000417\member{start}, \member{stop} and \member{step} attributes are the
418values of the expressions given as lower bound, upper bound and
419stride, respectively, substituting \code{None} for missing
420expressions.
Fred Drake99cd5731999-02-12 20:40:09 +0000421\withsubitem{(slice object attribute)}{\ttindex{start}
422 \ttindex{stop}\ttindex{step}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000423
Fred Drake2829f1c2001-06-23 05:27:20 +0000424
Fred Drake020f8c01998-07-28 19:32:59 +0000425\subsection{Calls\label{calls}}
Fred Drakef6669171998-05-06 19:52:49 +0000426\index{call}
427
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000428A call calls a callable object (e.g., a function) with a possibly empty
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000429series of arguments:
Fred Drakef6669171998-05-06 19:52:49 +0000430\obindex{callable}
431
Fred Drakecb4638a2001-07-06 22:49:53 +0000432\begin{productionlist}
433 \production{call}
434 {\token{primary} "(" [\token{argument_list} [","]] ")"}
435 \production{argument_list}
Fred Drake74653822002-10-07 16:28:38 +0000436 {\token{positional_arguments} ["," \token{keyword_arguments}]}
437 \productioncont{ ["," "*" \token{expression}]}
438 \productioncont{ ["," "**" \token{expression}]}
439 \productioncont{| \token{keyword_arguments} ["," "*" \token{expression}]}
440 \productioncont{ ["," "**" \token{expression}]}
Fred Drake53815882002-03-15 23:21:37 +0000441 \productioncont{| "*" \token{expression} ["," "**" \token{expression}]}
442 \productioncont{| "**" \token{expression}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000443 \production{positional_arguments}
444 {\token{expression} ("," \token{expression})*}
445 \production{keyword_arguments}
446 {\token{keyword_item} ("," \token{keyword_item})*}
447 \production{keyword_item}
448 {\token{identifier} "=" \token{expression}}
449\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000450
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000451A trailing comma may be present after an argument list but does not
452affect the semantics.
453
Fred Drakef6669171998-05-06 19:52:49 +0000454The primary must evaluate to a callable object (user-defined
455functions, built-in functions, methods of built-in objects, class
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000456objects, methods of class instances, and certain class instances
457themselves are callable; extensions may define additional callable
458object types). All argument expressions are evaluated before the call
459is attempted. Please refer to section \ref{function} for the syntax
460of formal parameter lists.
461
462If keyword arguments are present, they are first converted to
463positional arguments, as follows. First, a list of unfilled slots is
464created for the formal parameters. If there are N positional
465arguments, they are placed in the first N slots. Next, for each
466keyword argument, the identifier is used to determine the
467corresponding slot (if the identifier is the same as the first formal
468parameter name, the first slot is used, and so on). If the slot is
469already filled, a \exception{TypeError} exception is raised.
470Otherwise, the value of the argument is placed in the slot, filling it
471(even if the expression is \code{None}, it fills the slot). When all
472arguments have been processed, the slots that are still unfilled are
473filled with the corresponding default value from the function
474definition. (Default values are calculated, once, when the function
475is defined; thus, a mutable object such as a list or dictionary used
476as default value will be shared by all calls that don't specify an
477argument value for the corresponding slot; this should usually be
478avoided.) If there are any unfilled slots for which no default value
479is specified, a \exception{TypeError} exception is raised. Otherwise,
480the list of filled slots is used as the argument list for the call.
481
482If there are more positional arguments than there are formal parameter
483slots, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000484parameter using the syntax \samp{*identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000485case, that formal parameter receives a tuple containing the excess
486positional arguments (or an empty tuple if there were no excess
487positional arguments).
488
489If any keyword argument does not correspond to a formal parameter
490name, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000491parameter using the syntax \samp{**identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000492case, that formal parameter receives a dictionary containing the
493excess keyword arguments (using the keywords as keys and the argument
494values as corresponding values), or a (new) empty dictionary if there
495were no excess keyword arguments.
496
Michael W. Hudson850d3982001-12-12 11:56:33 +0000497If the syntax \samp{*expression} appears in the function call,
498\samp{expression} must evaluate to a sequence. Elements from this
499sequence are treated as if they were additional positional arguments;
500if there are postional arguments \var{x1},...,\var{xN} , and
501\samp{expression} evaluates to a sequence \var{y1},...,\var{yM}, this
502is equivalent to a call with M+N positional arguments
503\var{x1},...,\var{xN},\var{y1},...,\var{yM}.
504
505A consequence of this is that although the \samp{*expression} syntax
506appears \emph{after} any keyword arguments, it is processed
Fred Drakeb062cb22001-12-14 16:57:31 +0000507\emph{before} the keyword arguments (and the
508\samp{**expression} argument, if any -- see below). So:
Michael W. Hudson850d3982001-12-12 11:56:33 +0000509
510\begin{verbatim}
511>>> def f(a, b):
512... print a, b
513...
514>>> f(b=1, *(2,))
5152 1
516>>> f(a=1, *(2,))
517Traceback (most recent call last):
518 File "<stdin>", line 1, in ?
519TypeError: f() got multiple values for keyword argument 'a'
520>>> f(1, *(2,))
5211 2
522\end{verbatim}
523
Fred Drakeb062cb22001-12-14 16:57:31 +0000524It is unusual for both keyword arguments and the
525\samp{*expression} syntax to be used in the same call, so in practice
526this confusion does not arise.
Michael W. Hudson850d3982001-12-12 11:56:33 +0000527
528If the syntax \samp{**expression} appears in the function call,
529\samp{expression} must evaluate to a (subclass of) dictionary, the
530contents of which are treated as additional keyword arguments. In the
531case of a keyword appearing in both \samp{expression} and as an
532explicit keyword argument, a \exception{TypeError} exception is
533raised.
534
Fred Drakeea81edf1998-11-25 17:51:15 +0000535Formal parameters using the syntax \samp{*identifier} or
536\samp{**identifier} cannot be used as positional argument slots or
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000537as keyword argument names. Formal parameters using the syntax
Fred Drakeea81edf1998-11-25 17:51:15 +0000538\samp{(sublist)} cannot be used as keyword argument names; the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000539outermost sublist corresponds to a single unnamed argument slot, and
540the argument value is assigned to the sublist using the usual tuple
541assignment rules after all other parameter processing is done.
Fred Drakef6669171998-05-06 19:52:49 +0000542
Fred Drake5c07d9b1998-05-14 19:37:06 +0000543A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000544raises an exception. How this value is computed depends on the type
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000545of the callable object.
546
547If it is---
Fred Drakef6669171998-05-06 19:52:49 +0000548
549\begin{description}
550
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000551\item[a user-defined function:] The code block for the function is
Fred Drakef6669171998-05-06 19:52:49 +0000552executed, passing it the argument list. The first thing the code
553block will do is bind the formal parameters to the arguments; this is
554described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000555\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000556function call.
557\indexii{function}{call}
558\indexiii{user-defined}{function}{call}
559\obindex{user-defined function}
560\obindex{function}
561
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000562\item[a built-in function or method:] The result is up to the
Fred Drake3d83fc32000-07-31 20:08:23 +0000563interpreter; see the \citetitle[../lib/built-in-funcs.html]{Python
564Library Reference} for the descriptions of built-in functions and
565methods.
Fred Drakef6669171998-05-06 19:52:49 +0000566\indexii{function}{call}
567\indexii{built-in function}{call}
568\indexii{method}{call}
569\indexii{built-in method}{call}
570\obindex{built-in method}
571\obindex{built-in function}
572\obindex{method}
573\obindex{function}
574
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000575\item[a class object:] A new instance of that class is returned.
Fred Drakef6669171998-05-06 19:52:49 +0000576\obindex{class}
577\indexii{class object}{call}
578
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000579\item[a class instance method:] The corresponding user-defined
Fred Drakef6669171998-05-06 19:52:49 +0000580function is called, with an argument list that is one longer than the
581argument list of the call: the instance becomes the first argument.
582\obindex{class instance}
583\obindex{instance}
Fred Drakef6669171998-05-06 19:52:49 +0000584\indexii{class instance}{call}
585
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000586\item[a class instance:] The class must define a \method{__call__()}
587method; the effect is then the same as if that method was called.
588\indexii{instance}{call}
Fred Drakeea81edf1998-11-25 17:51:15 +0000589\withsubitem{(object method)}{\ttindex{__call__()}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000590
Fred Drakef6669171998-05-06 19:52:49 +0000591\end{description}
592
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000593
Fred Drake020f8c01998-07-28 19:32:59 +0000594\section{The power operator\label{power}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000595
596The power operator binds more tightly than unary operators on its
597left; it binds less tightly than unary operators on its right. The
598syntax is:
599
Fred Drakecb4638a2001-07-06 22:49:53 +0000600\begin{productionlist}
601 \production{power}
602 {\token{primary} ["**" \token{u_expr}]}
603\end{productionlist}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000604
605Thus, in an unparenthesized sequence of power and unary operators, the
606operators are evaluated from right to left (this does not constrain
607the evaluation order for the operands).
608
609The power operator has the same semantics as the built-in
610\function{pow()} function, when called with two arguments: it yields
611its left argument raised to the power of its right argument. The
612numeric arguments are first converted to a common type. The result
Raymond Hettinger0da7f392002-11-08 05:30:23 +0000613type is that of the arguments after coercion.
614
615With mixed operand types, the coercion rules for binary arithmetic
616operators apply. For int and long int operands, the result has the
617same type as the operands (after coercion) unless the second argument
618is negative; in that case, all arguments are converted to float and a
619float result is delivered. For example, \code{10**2} returns \code{100},
620but \code{10**-2} returns \code{0.01}. (This last feature was added in
621Python 2.2. In Python 2.1 and before, if both arguments were of integer
622types and the second argument was negative, an exception was raised).
623
624Raising \code{0.0} to a negative power results in a
625\exception{ZeroDivisionError}. Raising a negative number to a
626fractional power results in a \exception{ValueError}.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000627
628
Fred Drakee15956b2000-04-03 04:51:13 +0000629\section{Unary arithmetic operations \label{unary}}
Fred Drakef6669171998-05-06 19:52:49 +0000630\indexiii{unary}{arithmetic}{operation}
631\indexiii{unary}{bit-wise}{operation}
632
633All unary arithmetic (and bit-wise) operations have the same priority:
634
Fred Drakecb4638a2001-07-06 22:49:53 +0000635\begin{productionlist}
636 \production{u_expr}
637 {\token{power} | "-" \token{u_expr}
Fred Drakef6eafc32002-03-18 16:47:14 +0000638 | "+" \token{u_expr} | "{\~}" \token{u_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000639\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000640
Fred Drake5c07d9b1998-05-14 19:37:06 +0000641The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000642numeric argument.
643\index{negation}
644\index{minus}
645
Fred Drake5c07d9b1998-05-14 19:37:06 +0000646The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000647unchanged.
648\index{plus}
649
Fred Drakee15956b2000-04-03 04:51:13 +0000650The unary \code{\~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000651of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000652\code{x} is defined as \code{-(x+1)}. It only applies to integral
653numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000654\index{inversion}
655
656In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000657a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000658\exindex{TypeError}
659
Fred Drake2829f1c2001-06-23 05:27:20 +0000660
Fred Drake020f8c01998-07-28 19:32:59 +0000661\section{Binary arithmetic operations\label{binary}}
Fred Drakef6669171998-05-06 19:52:49 +0000662\indexiii{binary}{arithmetic}{operation}
663
664The binary arithmetic operations have the conventional priority
665levels. Note that some of these operations also apply to certain
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000666non-numeric types. Apart from the power operator, there are only two
667levels, one for multiplicative operators and one for additive
Fred Drakef6669171998-05-06 19:52:49 +0000668operators:
669
Fred Drakecb4638a2001-07-06 22:49:53 +0000670\begin{productionlist}
671 \production{m_expr}
672 {\token{u_expr} | \token{m_expr} "*" \token{u_expr}
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000673 | \token{m_expr} "//" \token{u_expr}
Fred Drake53815882002-03-15 23:21:37 +0000674 | \token{m_expr} "/" \token{u_expr}}
675 \productioncont{| \token{m_expr} "\%" \token{u_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000676 \production{a_expr}
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000677 {\token{m_expr} | \token{a_expr} "+" \token{m_expr}
678 | \token{a_expr} "-" \token{m_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000679\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000680
Fred Drake5c07d9b1998-05-14 19:37:06 +0000681The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000682arguments. The arguments must either both be numbers, or one argument
Fred Drakec3b18d72000-12-07 04:54:02 +0000683must be an integer (plain or long) and the other must be a sequence.
684In the former case, the numbers are converted to a common type and
685then multiplied together. In the latter case, sequence repetition is
Fred Drakef6669171998-05-06 19:52:49 +0000686performed; a negative repetition factor yields an empty sequence.
687\index{multiplication}
688
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000689The \code{/} (division) and \code{//} (floor division) operators yield
690the quotient of their arguments. The numeric arguments are first
691converted to a common type. Plain or long integer division yields an
692integer of the same type; the result is that of mathematical division
693with the `floor' function applied to the result. Division by zero
694raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000695\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000696\exindex{ZeroDivisionError}
697\index{division}
698
Fred Drake5c07d9b1998-05-14 19:37:06 +0000699The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000700division of the first argument by the second. The numeric arguments
701are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000702the \exception{ZeroDivisionError} exception. The arguments may be floating
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000703point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000704\code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
705yields a result with the same sign as its second operand (or zero);
Tim Peters5b21df42002-11-24 20:23:04 +0000706the absolute value of the result is strictly smaller than the absolute
707value of the second operand\footnote{
Gustavo Niemeyerf9554122002-11-26 18:14:35 +0000708 While \code{abs(x\%y) < abs(y)} is true mathematically, for
Tim Peters5b21df42002-11-24 20:23:04 +0000709 floats it may not be true numerically due to roundoff. For
710 example, and assuming a platform on which a Python float is an
711 IEEE 754 double-precision number, in order that \code{-1e-100 \% 1e100}
712 have the same sign as \code{1e100}, the computed result is
713 \code{-1e-100 + 1e100}, which is numerically exactly equal
714 to \code{1e100}. Function \function{fmod()} in the \module{math}
715 module returns a result whose sign matches the sign of the
716 first argument instead, and so returns \code{-1e-100} in this case.
717 Which approach is more appropriate depends on the application.
718}.
Fred Drakef6669171998-05-06 19:52:49 +0000719\index{modulo}
720
721The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000722following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
723modulo are also connected with the built-in function \function{divmod()}:
724\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Raymond Hettinger6cf09f02002-05-21 18:19:49 +0000725floating point numbers; there similar identities hold
Raymond Hettingerdaa34042003-06-26 17:41:40 +0000726approximately where \code{x/y} is replaced by \code{floor(x/y)} or
Tim Peters5b21df42002-11-24 20:23:04 +0000727\code{floor(x/y) - 1}\footnote{
Fred Drake1ea7c751999-05-06 14:46:35 +0000728 If x is very close to an exact integer multiple of y, it's
729 possible for \code{floor(x/y)} to be one larger than
730 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
731 the latter result, in order to preserve that \code{divmod(x,y)[0]
732 * y + x \%{} y} be very close to \code{x}.
Raymond Hettinger6cf09f02002-05-21 18:19:49 +0000733}.
734
Raymond Hettinger463bfaf2002-10-11 21:08:02 +0000735\deprecated{2.3}{The floor division operator, the modulo operator,
736and the \function{divmod()} function are no longer defined for complex
737numbers. Instead, convert to a floating point number using the
738\function{abs()} function if appropriate.}
Fred Drakef6669171998-05-06 19:52:49 +0000739
Fred Drake5c07d9b1998-05-14 19:37:06 +0000740The \code{+} (addition) operator yields the sum of its arguments.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000741The arguments must either both be numbers or both sequences of the
Fred Drakef6669171998-05-06 19:52:49 +0000742same type. In the former case, the numbers are converted to a common
743type and then added together. In the latter case, the sequences are
744concatenated.
745\index{addition}
746
Fred Drake5c07d9b1998-05-14 19:37:06 +0000747The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000748arguments. The numeric arguments are first converted to a common
749type.
750\index{subtraction}
751
Fred Drake2829f1c2001-06-23 05:27:20 +0000752
Fred Drake020f8c01998-07-28 19:32:59 +0000753\section{Shifting operations\label{shifting}}
Fred Drakef6669171998-05-06 19:52:49 +0000754\indexii{shifting}{operation}
755
756The shifting operations have lower priority than the arithmetic
757operations:
758
Fred Drakecb4638a2001-07-06 22:49:53 +0000759\begin{productionlist}
760 \production{shift_expr}
761 {\token{a_expr}
762 | \token{shift_expr} ( "<<" | ">>" ) \token{a_expr}}
763\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000764
765These operators accept plain or long integers as arguments. The
766arguments are converted to a common type. They shift the first
767argument to the left or right by the number of bits given by the
768second argument.
769
770A right shift by \var{n} bits is defined as division by
771\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
772multiplication with \code{pow(2,\var{n})}; for plain integers there is
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000773no overflow check so in that case the operation drops bits and flips
774the sign if the result is not less than \code{pow(2,31)} in absolute
775value. Negative shift counts raise a \exception{ValueError}
776exception.
Fred Drakef6669171998-05-06 19:52:49 +0000777\exindex{ValueError}
778
Fred Drake2829f1c2001-06-23 05:27:20 +0000779
Fred Drake020f8c01998-07-28 19:32:59 +0000780\section{Binary bit-wise operations\label{bitwise}}
Fred Drakef6669171998-05-06 19:52:49 +0000781\indexiii{binary}{bit-wise}{operation}
782
783Each of the three bitwise operations has a different priority level:
784
Fred Drakecb4638a2001-07-06 22:49:53 +0000785\begin{productionlist}
786 \production{and_expr}
787 {\token{shift_expr} | \token{and_expr} "\&" \token{shift_expr}}
788 \production{xor_expr}
789 {\token{and_expr} | \token{xor_expr} "\textasciicircum" \token{and_expr}}
790 \production{or_expr}
791 {\token{xor_expr} | \token{or_expr} "|" \token{xor_expr}}
792\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000793
Fred Drake5c07d9b1998-05-14 19:37:06 +0000794The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000795must be plain or long integers. The arguments are converted to a
796common type.
797\indexii{bit-wise}{and}
798
Fred Drake5c07d9b1998-05-14 19:37:06 +0000799The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000800arguments, which must be plain or long integers. The arguments are
801converted to a common type.
802\indexii{bit-wise}{xor}
803\indexii{exclusive}{or}
804
Fred Drake5c07d9b1998-05-14 19:37:06 +0000805The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000806arguments, which must be plain or long integers. The arguments are
807converted to a common type.
808\indexii{bit-wise}{or}
809\indexii{inclusive}{or}
810
Fred Drake2829f1c2001-06-23 05:27:20 +0000811
Fred Drake020f8c01998-07-28 19:32:59 +0000812\section{Comparisons\label{comparisons}}
Fred Drakef6669171998-05-06 19:52:49 +0000813\index{comparison}
814
Fred Drake1156f622000-09-19 18:10:05 +0000815Unlike C, all comparison operations in Python have the same priority,
816which is lower than that of any arithmetic, shifting or bitwise
817operation. Also unlike C, expressions like \code{a < b < c} have the
818interpretation that is conventional in mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000819\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000820
Fred Drakecb4638a2001-07-06 22:49:53 +0000821\begin{productionlist}
822 \production{comparison}
823 {\token{or_expr} ( \token{comp_operator} \token{or_expr} )*}
824 \production{comp_operator}
Fred Drake53815882002-03-15 23:21:37 +0000825 {"<" | ">" | "==" | ">=" | "<=" | "<>" | "!="}
826 \productioncont{| "is" ["not"] | ["not"] "in"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000827\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000828
Raymond Hettingerb268f032003-06-06 02:52:14 +0000829Comparisons yield boolean values: \code{True} or \code{False}.
Fred Drakef6669171998-05-06 19:52:49 +0000830
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000831Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
Fred Drakef6669171998-05-06 19:52:49 +0000832equivalent to \code{x < y and y <= z}, except that \code{y} is
833evaluated only once (but in both cases \code{z} is not evaluated at all
834when \code{x < y} is found to be false).
835\indexii{chaining}{comparisons}
836
837Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
838expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
839operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000840to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
Fred Drakef6669171998-05-06 19:52:49 +0000841\var{y opy z}, except that each expression is evaluated at most once.
842
843Note that \var{a opa b opb c} doesn't imply any kind of comparison
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000844between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
Fred Drakef6669171998-05-06 19:52:49 +0000845perfectly legal (though perhaps not pretty).
846
Fred Drake5c07d9b1998-05-14 19:37:06 +0000847The forms \code{<>} and \code{!=} are equivalent; for consistency with
848C, \code{!=} is preferred; where \code{!=} is mentioned below
Fred Drake1156f622000-09-19 18:10:05 +0000849\code{<>} is also accepted. The \code{<>} spelling is considered
850obsolescent.
Fred Drakef6669171998-05-06 19:52:49 +0000851
Fred Drake1156f622000-09-19 18:10:05 +0000852The operators \code{<}, \code{>}, \code{==}, \code{>=}, \code{<=}, and
853\code{!=} compare
854the values of two objects. The objects need not have the same type.
Fred Drakefd867712002-04-09 14:39:10 +0000855If both are numbers, they are converted to a common type. Otherwise,
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000856objects of different types \emph{always} compare unequal, and are
Fred Drakef6669171998-05-06 19:52:49 +0000857ordered consistently but arbitrarily.
858
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000859(This unusual definition of comparison was used to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000860definition of operations like sorting and the \keyword{in} and
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000861\keyword{not in} operators. In the future, the comparison rules for
862objects of different types are likely to change.)
Fred Drakef6669171998-05-06 19:52:49 +0000863
864Comparison of objects of the same type depends on the type:
865
866\begin{itemize}
867
868\item
869Numbers are compared arithmetically.
870
871\item
872Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +0000873(the result of the built-in function \function{ord()}) of their
Fred Drake1156f622000-09-19 18:10:05 +0000874characters. Unicode and 8-bit strings are fully interoperable in this
875behavior.
Fred Drakef6669171998-05-06 19:52:49 +0000876
877\item
878Tuples and lists are compared lexicographically using comparison of
Raymond Hettingerdaa34042003-06-26 17:41:40 +0000879corresponding elements. This means that to compare equal, each
880element must compare equal and the two sequences must be of the same
881type and have the same length.
882
883If not equal, the sequences are ordered the same as their first
884differing elements. For example, \code{cmp([1,2,x], [1,2,y])} returns
885the same as \code{cmp(x,y)}. If the corresponding element does not
886exist, the shorter sequence is ordered first (for example,
887\code{[1,2] < [1,2,3]}).
Fred Drakef6669171998-05-06 19:52:49 +0000888
889\item
Tim Peters20524db2001-10-01 20:22:45 +0000890Mappings (dictionaries) compare equal if and only if their sorted
891(key, value) lists compare equal.\footnote{The implementation computes
892 this efficiently, without constructing lists or sorting.}
893Outcomes other than equality are resolved consistently, but are not
Tim Peters1350c072001-10-01 20:25:26 +0000894otherwise defined.\footnote{Earlier versions of Python used
Tim Peters20524db2001-10-01 20:22:45 +0000895 lexicographic comparison of the sorted (key, value) lists, but this
896 was very expensive for the common case of comparing for equality. An
897 even earlier version of Python compared dictionaries by identity only,
898 but this caused surprises because people expected to be able to test
899 a dictionary for emptiness by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +0000900
901\item
902Most other types compare unequal unless they are the same object;
903the choice whether one object is considered smaller or larger than
904another one is made arbitrarily but consistently within one
905execution of a program.
906
907\end{itemize}
908
Fred Drake7399b9e2000-07-11 19:43:47 +0000909The operators \keyword{in} and \keyword{not in} test for set
Fred Drakeac79e952001-03-06 07:32:11 +0000910membership. \code{\var{x} in \var{s}} evaluates to true if \var{x}
911is a member of the set \var{s}, and false otherwise. \code{\var{x}
912not in \var{s}} returns the negation of \code{\var{x} in \var{s}}.
913The set membership test has traditionally been bound to sequences; an
914object is a member of a set if the set is a sequence and contains an
915element equal to that object. However, it is possible for an object
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +0000916to support membership tests without being a sequence. In particular,
917dictionaries support memership testing as a nicer way of spelling
918\code{\var{key} in \var{dict}}; other mapping types may follow suit.
Fred Drake7399b9e2000-07-11 19:43:47 +0000919
Fred Drake34bafcc2001-01-14 02:57:14 +0000920For the list and tuple types, \code{\var{x} in \var{y}} is true if and
Fred Drakeac79e952001-03-06 07:32:11 +0000921only if there exists an index \var{i} such that
Fred Drake34bafcc2001-01-14 02:57:14 +0000922\code{\var{x} == \var{y}[\var{i}]} is true.
Fred Drake7399b9e2000-07-11 19:43:47 +0000923
Fred Drake1156f622000-09-19 18:10:05 +0000924For the Unicode and string types, \code{\var{x} in \var{y}} is true if
Raymond Hettingerd0cda1d2003-06-26 19:32:10 +0000925and only if \var{x} is a substring of \var{y}. An equivalent test is
926\code{y.find(x) != -1}. Note, \var{x} and \var{y} need not be the
927same type; consequently, \code{u'ab' in 'abc'} will return \code{True}.
928Empty strings are always considered to be a substring of any other string,
929so \code{"" in "abc"} will return \code{True}.
930\versionchanged[Previously, \var{x} was required to be a string of
931length \code{1}]{2.3}
Fred Drake7399b9e2000-07-11 19:43:47 +0000932
933For user-defined classes which define the \method{__contains__()} method,
934\code{\var{x} in \var{y}} is true if and only if
935\code{\var{y}.__contains__(\var{x})} is true.
936
937For user-defined classes which do not define \method{__contains__()} and
Fred Drake1156f622000-09-19 18:10:05 +0000938do define \method{__getitem__()}, \code{\var{x} in \var{y}} is true if
939and only if there is a non-negative integer index \var{i} such that
Fred Drake7399b9e2000-07-11 19:43:47 +0000940\code{\var{x} == \var{y}[\var{i}]}, and all lower integer indices
941do not raise \exception{IndexError} exception. (If any other exception
942is raised, it is as if \keyword{in} raised that exception).
943
944The operator \keyword{not in} is defined to have the inverse true value
945of \keyword{in}.
Fred Drakef6669171998-05-06 19:52:49 +0000946\opindex{in}
947\opindex{not in}
948\indexii{membership}{test}
949\obindex{sequence}
950
Fred Drake5c07d9b1998-05-14 19:37:06 +0000951The operators \keyword{is} and \keyword{is not} test for object identity:
952\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
953are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +0000954truth value.
955\opindex{is}
956\opindex{is not}
957\indexii{identity}{test}
958
Fred Drake2829f1c2001-06-23 05:27:20 +0000959
Fred Drake020f8c01998-07-28 19:32:59 +0000960\section{Boolean operations\label{Booleans}}
Fred Drakef6669171998-05-06 19:52:49 +0000961\indexii{Boolean}{operation}
962
963Boolean operations have the lowest priority of all Python operations:
964
Fred Drakecb4638a2001-07-06 22:49:53 +0000965\begin{productionlist}
966 \production{expression}
967 {\token{or_test} | \token{lambda_form}}
968 \production{or_test}
969 {\token{and_test} | \token{or_test} "or" \token{and_test}}
970 \production{and_test}
971 {\token{not_test} | \token{and_test} "and" \token{not_test}}
972 \production{not_test}
973 {\token{comparison} | "not" \token{not_test}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000974\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000975
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000976In the context of Boolean operations, and also when expressions are
Fred Drakef6669171998-05-06 19:52:49 +0000977used by control flow statements, the following values are interpreted
Fred Drake5c07d9b1998-05-14 19:37:06 +0000978as false: \code{None}, numeric zero of all types, empty sequences
Fred Drakef6669171998-05-06 19:52:49 +0000979(strings, tuples and lists), and empty mappings (dictionaries). All
980other values are interpreted as true.
981
Raymond Hettinger46a16f22004-04-23 17:11:47 +0000982The operator \keyword{not} yields \code{True} if its argument is false,
983\code{False} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +0000984\opindex{not}
985
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000986The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000987\var{x} is false, its value is returned; otherwise, \var{y} is
988evaluated and the resulting value is returned.
989\opindex{and}
990
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000991The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000992\var{x} is true, its value is returned; otherwise, \var{y} is
993evaluated and the resulting value is returned.
994\opindex{or}
995
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000996(Note that neither \keyword{and} nor \keyword{or} restrict the value
Raymond Hettinger46a16f22004-04-23 17:11:47 +0000997and type they return to \code{False} and \code{True}, but rather return the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000998last evaluated argument.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000999This is sometimes useful, e.g., if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +00001000replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +00001001\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +00001002invent a value anyway, it does not bother to return a value of the
Raymond Hettinger46a16f22004-04-23 17:11:47 +00001003same type as its argument, so e.g., \code{not 'foo'} yields \code{False},
Fred Drake5c07d9b1998-05-14 19:37:06 +00001004not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +00001005
Jeremy Hylton2225add2002-04-01 21:05:21 +00001006\section{Lambdas\label{lambdas}}
1007\indexii{lambda}{expression}
1008\indexii{lambda}{form}
Martin v. Löwis95cf84a2003-10-19 07:32:24 +00001009\indexii{anonymous}{function}
Jeremy Hylton2225add2002-04-01 21:05:21 +00001010
Martin v. Löwis477c8562004-06-02 12:54:33 +00001011\begin{productionlist}
1012 \production{lambda_form}
1013 {"lambda" [\token{parameter_list}]: \token{expression}}
1014\end{productionlist}
1015
Fred Drakef6669171998-05-06 19:52:49 +00001016Lambda forms (lambda expressions) have the same syntactic position as
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001017expressions. They are a shorthand to create anonymous functions; the
1018expression \code{lambda \var{arguments}: \var{expression}}
Jeremy Hylton2225add2002-04-01 21:05:21 +00001019yields a function object. The unnamed object behaves like a function
Raymond Hettinger7fd9ced2002-06-25 04:04:14 +00001020object defined with
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001021
1022\begin{verbatim}
1023def name(arguments):
1024 return expression
1025\end{verbatim}
1026
1027See section \ref{function} for the syntax of parameter lists. Note
1028that functions created with lambda forms cannot contain statements.
Fred Drakef6669171998-05-06 19:52:49 +00001029\label{lambda}
Fred Drake88382692001-06-05 02:17:02 +00001030
Fred Drake020f8c01998-07-28 19:32:59 +00001031\section{Expression lists\label{exprlists}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001032\indexii{expression}{list}
Fred Drakef6669171998-05-06 19:52:49 +00001033
Fred Drakecb4638a2001-07-06 22:49:53 +00001034\begin{productionlist}
1035 \production{expression_list}
1036 {\token{expression} ( "," \token{expression} )* [","]}
1037\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +00001038
Fred Drakec009d192000-04-25 21:09:10 +00001039An expression list containing at least one comma yields a
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001040tuple. The length of the tuple is the number of expressions in the
1041list. The expressions are evaluated from left to right.
Fred Drakef6669171998-05-06 19:52:49 +00001042\obindex{tuple}
1043
1044The trailing comma is required only to create a single tuple (a.k.a. a
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001045\emph{singleton}); it is optional in all other cases. A single
Fred Drakec009d192000-04-25 21:09:10 +00001046expression without a trailing comma doesn't create a
1047tuple, but rather yields the value of that expression.
Fred Drakef6669171998-05-06 19:52:49 +00001048(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +00001049\code{()}.)
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001050\indexii{trailing}{comma}
Fred Drakef6669171998-05-06 19:52:49 +00001051
Gustavo Niemeyer78429a62002-12-16 13:54:02 +00001052\section{Evaluation order\label{evalorder}}
1053\indexii{evaluation}{order}
1054
1055Python evaluates expressions from left to right. Notice that while
1056evaluating an assignment, the right-hand side is evaluated before
1057the left-hand side.
1058
1059In the following lines, expressions will be evaluated in the
1060arithmetic order of their suffixes:
1061
1062\begin{verbatim}
1063expr1, expr2, expr3, expr4
1064(expr1, expr2, expr3, expr4)
1065{expr1: expr2, expr3: expr4}
1066expr1 + expr2 * (expr3 - expr4)
1067func(expr1, expr2, *expr3, **expr4)
1068expr3, expr4 = expr1, expr2
1069\end{verbatim}
Fred Draked09120b1999-04-29 16:43:42 +00001070
Fred Drake020f8c01998-07-28 19:32:59 +00001071\section{Summary\label{summary}}
Fred Drakef6669171998-05-06 19:52:49 +00001072
Fred Draked09120b1999-04-29 16:43:42 +00001073The following table summarizes the operator
1074precedences\indexii{operator}{precedence} in Python, from lowest
1075precedence (least binding) to highest precedence (most binding).
1076Operators in the same box have the same precedence. Unless the syntax
1077is explicitly given, operators are binary. Operators in the same box
Alex Martellic516b0e2003-11-09 16:33:56 +00001078group left to right (except for comparisons, including tests, which all
1079have the same precedence and chain from left to right --- see section
1080\ref{comparisons} -- and exponentiation, which groups from right to left).
Fred Drakef6669171998-05-06 19:52:49 +00001081
Fred Draked09120b1999-04-29 16:43:42 +00001082\begin{tableii}{c|l}{textrm}{Operator}{Description}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001083 \lineii{\keyword{lambda}} {Lambda expression}
1084 \hline
1085 \lineii{\keyword{or}} {Boolean OR}
1086 \hline
1087 \lineii{\keyword{and}} {Boolean AND}
1088 \hline
1089 \lineii{\keyword{not} \var{x}} {Boolean NOT}
1090 \hline
1091 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
1092 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
1093 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
Fred Drake9beee801998-10-21 00:44:49 +00001094 \code{<>}, \code{!=}, \code{==}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001095 {Comparisons}
1096 \hline
1097 \lineii{\code{|}} {Bitwise OR}
1098 \hline
1099 \lineii{\code{\^}} {Bitwise XOR}
1100 \hline
1101 \lineii{\code{\&}} {Bitwise AND}
1102 \hline
Fred Drake24e7a292001-04-12 12:37:03 +00001103 \lineii{\code{<}\code{<}, \code{>}\code{>}} {Shifts}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001104 \hline
1105 \lineii{\code{+}, \code{-}}{Addition and subtraction}
1106 \hline
Fred Drake9beee801998-10-21 00:44:49 +00001107 \lineii{\code{*}, \code{/}, \code{\%}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001108 {Multiplication, division, remainder}
1109 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001110 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
1111 \lineii{\code{\~\var{x}}} {Bitwise not}
1112 \hline
Fred Drakeb8ac0092001-05-09 16:51:49 +00001113 \lineii{\code{**}} {Exponentiation}
1114 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001115 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
1116 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
1117 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
1118 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
Fred Draked09120b1999-04-29 16:43:42 +00001119 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001120 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
1121 \lineii{\code{[\var{expressions}\ldots]}} {List display}
1122 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
1123 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
1124\end{tableii}