blob: 52bb57f68537e6ecf1e8e8b62b79e0e683c81087 [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
Thomas Wouters477c8d52006-05-27 19:21:47 +000025arguments are coerced using the coercion rules listed at
26~\ref{coercion-rules}. If both arguments are standard numeric types,
27the 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}}
Johannes Gijsbers71269762004-10-09 15:52:04 +000058 \productioncont{| \token{generator_expression} | \token{dict_display}}
Raymond Hettinger5c8d29c2004-08-15 23:28:10 +000059 \productioncont{| \token{string_conversion}}
Fred Drakecb4638a2001-07-06 22:49:53 +000060\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +000061
Fred Drake2829f1c2001-06-23 05:27:20 +000062
Fred Drake020f8c01998-07-28 19:32:59 +000063\subsection{Identifiers (Names)\label{atom-identifiers}}
Fred Drakef6669171998-05-06 19:52:49 +000064\index{name}
65\index{identifier}
66
Fred Drakec0678ff2003-09-06 03:33:32 +000067An identifier occurring as an atom is a name. See
68section~\ref{naming} for documentation of naming and binding.
Fred Drakef6669171998-05-06 19:52:49 +000069
70When the name is bound to an object, evaluation of the atom yields
71that object. When a name is not bound, an attempt to evaluate it
Fred Drake5c07d9b1998-05-14 19:37:06 +000072raises a \exception{NameError} exception.
Fred Drakef6669171998-05-06 19:52:49 +000073\exindex{NameError}
74
Fred Drakec0678ff2003-09-06 03:33:32 +000075\strong{Private name mangling:}
Guido van Rossum3a0ad601998-07-23 21:57:42 +000076\indexii{name}{mangling}%
77\indexii{private}{names}%
Fred Drakec0678ff2003-09-06 03:33:32 +000078When an identifier that textually occurs in a class definition begins
Guido van Rossum3a0ad601998-07-23 21:57:42 +000079with two or more underscore characters and does not end in two or more
Fred Drakeea81edf1998-11-25 17:51:15 +000080underscores, it is considered a \dfn{private name} of that class.
Guido van Rossum3a0ad601998-07-23 21:57:42 +000081Private names are transformed to a longer form before code is
82generated for them. The transformation inserts the class name in
83front of the name, with leading underscores removed, and a single
84underscore inserted in front of the class name. For example, the
85identifier \code{__spam} occurring in a class named \code{Ham} will be
86transformed to \code{_Ham__spam}. This transformation is independent
87of the syntactical context in which the identifier is used. If the
88transformed name is extremely long (longer than 255 characters),
89implementation defined truncation may happen. If the class name
90consists only of underscores, no transformation is done.
91
Fred Drake2829f1c2001-06-23 05:27:20 +000092
Fred Drake020f8c01998-07-28 19:32:59 +000093\subsection{Literals\label{atom-literals}}
Fred Drakef6669171998-05-06 19:52:49 +000094\index{literal}
95
Guido van Rossum3a0ad601998-07-23 21:57:42 +000096Python supports string literals and various numeric literals:
Fred Drakef6669171998-05-06 19:52:49 +000097
Fred Drakecb4638a2001-07-06 22:49:53 +000098\begin{productionlist}
99 \production{literal}
Fred Drake53815882002-03-15 23:21:37 +0000100 {\token{stringliteral} | \token{integer} | \token{longinteger}}
101 \productioncont{| \token{floatnumber} | \token{imagnumber}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000102\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000103
104Evaluation of a literal yields an object of the given type (string,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000105integer, long integer, floating point number, complex number) with the
106given value. The value may be approximated in the case of floating
107point and imaginary (complex) literals. See section \ref{literals}
108for details.
Fred Drakef6669171998-05-06 19:52:49 +0000109
110All literals correspond to immutable data types, and hence the
111object's identity is less important than its value. Multiple
112evaluations of literals with the same value (either the same
113occurrence in the program text or a different occurrence) may obtain
114the same object or a different object with the same value.
115\indexiii{immutable}{data}{type}
Fred Drakee15956b2000-04-03 04:51:13 +0000116\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000117
Fred Drake2829f1c2001-06-23 05:27:20 +0000118
Fred Drake020f8c01998-07-28 19:32:59 +0000119\subsection{Parenthesized forms\label{parenthesized}}
Fred Drakef6669171998-05-06 19:52:49 +0000120\index{parenthesized form}
121
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000122A parenthesized form is an optional expression list enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000123parentheses:
124
Fred Drakecb4638a2001-07-06 22:49:53 +0000125\begin{productionlist}
126 \production{parenth_form}
127 {"(" [\token{expression_list}] ")"}
128\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000129
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000130A parenthesized expression list yields whatever that expression list
131yields: if the list contains at least one comma, it yields a tuple;
132otherwise, it yields the single expression that makes up the
133expression list.
Fred Drakef6669171998-05-06 19:52:49 +0000134
135An empty pair of parentheses yields an empty tuple object. Since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000136tuples are immutable, the rules for literals apply (i.e., two
137occurrences of the empty tuple may or may not yield the same object).
Fred Drakef6669171998-05-06 19:52:49 +0000138\indexii{empty}{tuple}
139
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000140Note that tuples are not formed by the parentheses, but rather by use
Fred Drakef6669171998-05-06 19:52:49 +0000141of the comma operator. The exception is the empty tuple, for which
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000142parentheses \emph{are} required --- allowing unparenthesized ``nothing''
Fred Drakef6669171998-05-06 19:52:49 +0000143in expressions would cause ambiguities and allow common typos to
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000144pass uncaught.
Fred Drakef6669171998-05-06 19:52:49 +0000145\index{comma}
146\indexii{tuple}{display}
147
Fred Drake2829f1c2001-06-23 05:27:20 +0000148
Fred Drake020f8c01998-07-28 19:32:59 +0000149\subsection{List displays\label{lists}}
Fred Drakef6669171998-05-06 19:52:49 +0000150\indexii{list}{display}
Skip Montanarob6559392000-09-11 16:31:55 +0000151\indexii{list}{comprehensions}
Fred Drakef6669171998-05-06 19:52:49 +0000152
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000153A list display is a possibly empty series of expressions enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000154square brackets:
155
Fred Drakecb4638a2001-07-06 22:49:53 +0000156\begin{productionlist}
Fred Drake25b53582003-06-27 17:12:43 +0000157 \production{test}
Thomas Woutersdca3b9c2006-02-27 00:24:13 +0000158 {\token{or_test} | \token{lambda_form}}
Fred Drake25b53582003-06-27 17:12:43 +0000159 \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
Raymond Hettinger5c8d29c2004-08-15 23:28:10 +0000196\subsection{Generator expressions\label{genexpr}}
197\indexii{generator}{expression}
198
199A generator expression is a compact generator notation in parentheses:
200
201\begin{productionlist}
202 \production{generator_expression}
203 {"(" \token{test} \token{genexpr_for} ")"}
204 \production{genexpr_for}
205 {"for" \token{expression_list} "in" \token{test}
206 [\token{genexpr_iter}]}
207 \production{genexpr_iter}
208 {\token{genexpr_for} | \token{genexpr_if}}
209 \production{genexpr_if}
210 {"if" \token{test} [\token{genexpr_iter}]}
211\end{productionlist}
212
213A generator expression yields a new generator object.
214\obindex{generator}
215\obindex{generator expression}
216It consists of a single expression followed by at least one
217\keyword{for} clause and zero or more \keyword{for} or \keyword{if}
218clauses. The iterating values of the new generator are those that
219would be produced by considering each of the \keyword{for} or
220\keyword{if} clauses a block, nesting from left to right, and
221evaluating the expression to yield a value that is reached the
222innermost block for each iteration.
223
224Variables used in the generator expression are evaluated lazily
225when the \method{next()} method is called for generator object
226(in the same fashion as normal generators). However, the leftmost
227\keyword{for} clause is immediately evaluated so that error produced
228by it can be seen before any other possible error in the code that
229handles the generator expression.
230Subsequent \keyword{for} clauses cannot be evaluated immediately since
231they may depend on the previous \keyword{for} loop.
232For example: \samp{(x*y for x in range(10) for y in bar(x))}.
233
234The parentheses can be omitted on calls with only one argument.
235See section \ref{calls} for the detail.
236
237
Fred Drake020f8c01998-07-28 19:32:59 +0000238\subsection{Dictionary displays\label{dict}}
Fred Drakef6669171998-05-06 19:52:49 +0000239\indexii{dictionary}{display}
240
241A dictionary display is a possibly empty series of key/datum pairs
242enclosed in curly braces:
243\index{key}
244\index{datum}
245\index{key/datum pair}
246
Fred Drakecb4638a2001-07-06 22:49:53 +0000247\begin{productionlist}
248 \production{dict_display}
Fred Drake83d14c12002-03-16 06:35:54 +0000249 {"\{" [\token{key_datum_list}] "\}"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000250 \production{key_datum_list}
251 {\token{key_datum} ("," \token{key_datum})* [","]}
252 \production{key_datum}
253 {\token{expression} ":" \token{expression}}
254\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000255
256A dictionary display yields a new dictionary object.
257\obindex{dictionary}
258
259The key/datum pairs are evaluated from left to right to define the
260entries of the dictionary: each key object is used as a key into the
261dictionary to store the corresponding datum.
262
263Restrictions on the types of the key values are listed earlier in
Raymond Hettinger68804312005-01-01 00:28:46 +0000264section \ref{types}. (To summarize, the key type should be hashable,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000265which excludes all mutable objects.) Clashes between duplicate keys
266are not detected; the last datum (textually rightmost in the display)
267stored for a given key value prevails.
Fred Drakee15956b2000-04-03 04:51:13 +0000268\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000269
Fred Drake2829f1c2001-06-23 05:27:20 +0000270
Fred Drake020f8c01998-07-28 19:32:59 +0000271\section{Primaries\label{primaries}}
Fred Drakef6669171998-05-06 19:52:49 +0000272\index{primary}
273
274Primaries represent the most tightly bound operations of the language.
275Their syntax is:
276
Fred Drakecb4638a2001-07-06 22:49:53 +0000277\begin{productionlist}
278 \production{primary}
279 {\token{atom} | \token{attributeref}
280 | \token{subscription} | \token{slicing} | \token{call}}
281\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000282
Fred Drake2829f1c2001-06-23 05:27:20 +0000283
Fred Drake020f8c01998-07-28 19:32:59 +0000284\subsection{Attribute references\label{attribute-references}}
Fred Drakef6669171998-05-06 19:52:49 +0000285\indexii{attribute}{reference}
286
287An attribute reference is a primary followed by a period and a name:
288
Fred Drakecb4638a2001-07-06 22:49:53 +0000289\begin{productionlist}
290 \production{attributeref}
291 {\token{primary} "." \token{identifier}}
292\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000293
294The primary must evaluate to an object of a type that supports
Fred Drake34bafcc2001-01-14 02:57:14 +0000295attribute references, e.g., a module, list, or an instance. This
296object is then asked to produce the attribute whose name is the
297identifier. If this attribute is not available, the exception
Fred Drake5c07d9b1998-05-14 19:37:06 +0000298\exception{AttributeError}\exindex{AttributeError} is raised.
299Otherwise, the type and value of the object produced is determined by
300the object. Multiple evaluations of the same attribute reference may
301yield different objects.
Fred Drakef6669171998-05-06 19:52:49 +0000302\obindex{module}
303\obindex{list}
304
Fred Drake2829f1c2001-06-23 05:27:20 +0000305
Fred Drake020f8c01998-07-28 19:32:59 +0000306\subsection{Subscriptions\label{subscriptions}}
Fred Drakef6669171998-05-06 19:52:49 +0000307\index{subscription}
308
309A subscription selects an item of a sequence (string, tuple or list)
310or mapping (dictionary) object:
311\obindex{sequence}
312\obindex{mapping}
313\obindex{string}
314\obindex{tuple}
315\obindex{list}
316\obindex{dictionary}
317\indexii{sequence}{item}
318
Fred Drakecb4638a2001-07-06 22:49:53 +0000319\begin{productionlist}
320 \production{subscription}
321 {\token{primary} "[" \token{expression_list} "]"}
322\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000323
324The primary must evaluate to an object of a sequence or mapping type.
325
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000326If the primary is a mapping, the expression list must evaluate to an
327object whose value is one of the keys of the mapping, and the
328subscription selects the value in the mapping that corresponds to that
329key. (The expression list is a tuple except if it has exactly one
330item.)
Fred Drakef6669171998-05-06 19:52:49 +0000331
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000332If the primary is a sequence, the expression (list) must evaluate to a
333plain integer. If this value is negative, the length of the sequence
334is added to it (so that, e.g., \code{x[-1]} selects the last item of
335\code{x}.) The resulting value must be a nonnegative integer less
336than the number of items in the sequence, and the subscription selects
337the item whose index is that value (counting from zero).
Fred Drakef6669171998-05-06 19:52:49 +0000338
339A string's items are characters. A character is not a separate data
340type but a string of exactly one character.
341\index{character}
342\indexii{string}{item}
343
Fred Drake2829f1c2001-06-23 05:27:20 +0000344
Fred Drake020f8c01998-07-28 19:32:59 +0000345\subsection{Slicings\label{slicings}}
Fred Drakef6669171998-05-06 19:52:49 +0000346\index{slicing}
347\index{slice}
348
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000349A slicing selects a range of items in a sequence object (e.g., a
350string, tuple or list). Slicings may be used as expressions or as
Thomas Wouters477c8d52006-05-27 19:21:47 +0000351targets in assignment or \keyword{del} statements. The syntax for a
352slicing:
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} [","]] ")"}
Raymond Hettinger5c8d29c2004-08-15 23:28:10 +0000435 {\token{primary} "(" [\token{argument_list} [","] |
436 \token{test} \token{genexpr_for} ] ")"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000437 \production{argument_list}
Fred Drake74653822002-10-07 16:28:38 +0000438 {\token{positional_arguments} ["," \token{keyword_arguments}]}
439 \productioncont{ ["," "*" \token{expression}]}
440 \productioncont{ ["," "**" \token{expression}]}
441 \productioncont{| \token{keyword_arguments} ["," "*" \token{expression}]}
442 \productioncont{ ["," "**" \token{expression}]}
Fred Drake53815882002-03-15 23:21:37 +0000443 \productioncont{| "*" \token{expression} ["," "**" \token{expression}]}
444 \productioncont{| "**" \token{expression}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000445 \production{positional_arguments}
446 {\token{expression} ("," \token{expression})*}
447 \production{keyword_arguments}
448 {\token{keyword_item} ("," \token{keyword_item})*}
449 \production{keyword_item}
450 {\token{identifier} "=" \token{expression}}
451\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000452
Fred Drake9a408512004-11-02 18:57:33 +0000453A trailing comma may be present after the positional and keyword
454arguments but does not affect the semantics.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000455
Fred Drakef6669171998-05-06 19:52:49 +0000456The primary must evaluate to a callable object (user-defined
457functions, built-in functions, methods of built-in objects, class
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000458objects, methods of class instances, and certain class instances
459themselves are callable; extensions may define additional callable
460object types). All argument expressions are evaluated before the call
461is attempted. Please refer to section \ref{function} for the syntax
462of formal parameter lists.
463
464If keyword arguments are present, they are first converted to
465positional arguments, as follows. First, a list of unfilled slots is
466created for the formal parameters. If there are N positional
467arguments, they are placed in the first N slots. Next, for each
468keyword argument, the identifier is used to determine the
469corresponding slot (if the identifier is the same as the first formal
470parameter name, the first slot is used, and so on). If the slot is
471already filled, a \exception{TypeError} exception is raised.
472Otherwise, the value of the argument is placed in the slot, filling it
473(even if the expression is \code{None}, it fills the slot). When all
474arguments have been processed, the slots that are still unfilled are
475filled with the corresponding default value from the function
476definition. (Default values are calculated, once, when the function
477is defined; thus, a mutable object such as a list or dictionary used
478as default value will be shared by all calls that don't specify an
479argument value for the corresponding slot; this should usually be
480avoided.) If there are any unfilled slots for which no default value
481is specified, a \exception{TypeError} exception is raised. Otherwise,
482the list of filled slots is used as the argument list for the call.
483
484If there are more positional arguments than there are formal parameter
485slots, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000486parameter using the syntax \samp{*identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000487case, that formal parameter receives a tuple containing the excess
488positional arguments (or an empty tuple if there were no excess
489positional arguments).
490
491If any keyword argument does not correspond to a formal parameter
492name, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000493parameter using the syntax \samp{**identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000494case, that formal parameter receives a dictionary containing the
495excess keyword arguments (using the keywords as keys and the argument
496values as corresponding values), or a (new) empty dictionary if there
497were no excess keyword arguments.
498
Michael W. Hudson850d3982001-12-12 11:56:33 +0000499If the syntax \samp{*expression} appears in the function call,
500\samp{expression} must evaluate to a sequence. Elements from this
501sequence are treated as if they were additional positional arguments;
502if there are postional arguments \var{x1},...,\var{xN} , and
503\samp{expression} evaluates to a sequence \var{y1},...,\var{yM}, this
504is equivalent to a call with M+N positional arguments
505\var{x1},...,\var{xN},\var{y1},...,\var{yM}.
506
507A consequence of this is that although the \samp{*expression} syntax
508appears \emph{after} any keyword arguments, it is processed
Fred Drakeb062cb22001-12-14 16:57:31 +0000509\emph{before} the keyword arguments (and the
510\samp{**expression} argument, if any -- see below). So:
Michael W. Hudson850d3982001-12-12 11:56:33 +0000511
512\begin{verbatim}
513>>> def f(a, b):
514... print a, b
515...
516>>> f(b=1, *(2,))
5172 1
518>>> f(a=1, *(2,))
519Traceback (most recent call last):
520 File "<stdin>", line 1, in ?
521TypeError: f() got multiple values for keyword argument 'a'
522>>> f(1, *(2,))
5231 2
524\end{verbatim}
525
Fred Drakeb062cb22001-12-14 16:57:31 +0000526It is unusual for both keyword arguments and the
527\samp{*expression} syntax to be used in the same call, so in practice
528this confusion does not arise.
Michael W. Hudson850d3982001-12-12 11:56:33 +0000529
530If the syntax \samp{**expression} appears in the function call,
531\samp{expression} must evaluate to a (subclass of) dictionary, the
532contents of which are treated as additional keyword arguments. In the
533case of a keyword appearing in both \samp{expression} and as an
534explicit keyword argument, a \exception{TypeError} exception is
535raised.
536
Fred Drakeea81edf1998-11-25 17:51:15 +0000537Formal parameters using the syntax \samp{*identifier} or
538\samp{**identifier} cannot be used as positional argument slots or
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000539as keyword argument names. Formal parameters using the syntax
Fred Drakeea81edf1998-11-25 17:51:15 +0000540\samp{(sublist)} cannot be used as keyword argument names; the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000541outermost sublist corresponds to a single unnamed argument slot, and
542the argument value is assigned to the sublist using the usual tuple
543assignment rules after all other parameter processing is done.
Fred Drakef6669171998-05-06 19:52:49 +0000544
Fred Drake5c07d9b1998-05-14 19:37:06 +0000545A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000546raises an exception. How this value is computed depends on the type
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000547of the callable object.
548
549If it is---
Fred Drakef6669171998-05-06 19:52:49 +0000550
551\begin{description}
552
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000553\item[a user-defined function:] The code block for the function is
Fred Drakef6669171998-05-06 19:52:49 +0000554executed, passing it the argument list. The first thing the code
555block will do is bind the formal parameters to the arguments; this is
556described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000557\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000558function call.
559\indexii{function}{call}
560\indexiii{user-defined}{function}{call}
561\obindex{user-defined function}
562\obindex{function}
563
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000564\item[a built-in function or method:] The result is up to the
Fred Drake3d83fc32000-07-31 20:08:23 +0000565interpreter; see the \citetitle[../lib/built-in-funcs.html]{Python
566Library Reference} for the descriptions of built-in functions and
567methods.
Fred Drakef6669171998-05-06 19:52:49 +0000568\indexii{function}{call}
569\indexii{built-in function}{call}
570\indexii{method}{call}
571\indexii{built-in method}{call}
572\obindex{built-in method}
573\obindex{built-in function}
574\obindex{method}
575\obindex{function}
576
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000577\item[a class object:] A new instance of that class is returned.
Fred Drakef6669171998-05-06 19:52:49 +0000578\obindex{class}
579\indexii{class object}{call}
580
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000581\item[a class instance method:] The corresponding user-defined
Fred Drakef6669171998-05-06 19:52:49 +0000582function is called, with an argument list that is one longer than the
583argument list of the call: the instance becomes the first argument.
584\obindex{class instance}
585\obindex{instance}
Fred Drakef6669171998-05-06 19:52:49 +0000586\indexii{class instance}{call}
587
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000588\item[a class instance:] The class must define a \method{__call__()}
589method; the effect is then the same as if that method was called.
590\indexii{instance}{call}
Fred Drakeea81edf1998-11-25 17:51:15 +0000591\withsubitem{(object method)}{\ttindex{__call__()}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000592
Fred Drakef6669171998-05-06 19:52:49 +0000593\end{description}
594
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000595
Fred Drake020f8c01998-07-28 19:32:59 +0000596\section{The power operator\label{power}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000597
598The power operator binds more tightly than unary operators on its
599left; it binds less tightly than unary operators on its right. The
600syntax is:
601
Fred Drakecb4638a2001-07-06 22:49:53 +0000602\begin{productionlist}
603 \production{power}
604 {\token{primary} ["**" \token{u_expr}]}
605\end{productionlist}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000606
607Thus, in an unparenthesized sequence of power and unary operators, the
608operators are evaluated from right to left (this does not constrain
609the evaluation order for the operands).
610
611The power operator has the same semantics as the built-in
612\function{pow()} function, when called with two arguments: it yields
613its left argument raised to the power of its right argument. The
614numeric arguments are first converted to a common type. The result
Raymond Hettinger0da7f392002-11-08 05:30:23 +0000615type is that of the arguments after coercion.
616
617With mixed operand types, the coercion rules for binary arithmetic
618operators apply. For int and long int operands, the result has the
619same type as the operands (after coercion) unless the second argument
620is negative; in that case, all arguments are converted to float and a
621float result is delivered. For example, \code{10**2} returns \code{100},
622but \code{10**-2} returns \code{0.01}. (This last feature was added in
623Python 2.2. In Python 2.1 and before, if both arguments were of integer
624types and the second argument was negative, an exception was raised).
625
626Raising \code{0.0} to a negative power results in a
627\exception{ZeroDivisionError}. Raising a negative number to a
628fractional power results in a \exception{ValueError}.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000629
630
Fred Drakee15956b2000-04-03 04:51:13 +0000631\section{Unary arithmetic operations \label{unary}}
Fred Drakef6669171998-05-06 19:52:49 +0000632\indexiii{unary}{arithmetic}{operation}
633\indexiii{unary}{bit-wise}{operation}
634
635All unary arithmetic (and bit-wise) operations have the same priority:
636
Fred Drakecb4638a2001-07-06 22:49:53 +0000637\begin{productionlist}
638 \production{u_expr}
639 {\token{power} | "-" \token{u_expr}
Fred Drakef6eafc32002-03-18 16:47:14 +0000640 | "+" \token{u_expr} | "{\~}" \token{u_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000641\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000642
Fred Drake5c07d9b1998-05-14 19:37:06 +0000643The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000644numeric argument.
645\index{negation}
646\index{minus}
647
Fred Drake5c07d9b1998-05-14 19:37:06 +0000648The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000649unchanged.
650\index{plus}
651
Fred Drakee15956b2000-04-03 04:51:13 +0000652The unary \code{\~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000653of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000654\code{x} is defined as \code{-(x+1)}. It only applies to integral
655numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000656\index{inversion}
657
658In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000659a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000660\exindex{TypeError}
661
Fred Drake2829f1c2001-06-23 05:27:20 +0000662
Fred Drake020f8c01998-07-28 19:32:59 +0000663\section{Binary arithmetic operations\label{binary}}
Fred Drakef6669171998-05-06 19:52:49 +0000664\indexiii{binary}{arithmetic}{operation}
665
666The binary arithmetic operations have the conventional priority
667levels. Note that some of these operations also apply to certain
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000668non-numeric types. Apart from the power operator, there are only two
669levels, one for multiplicative operators and one for additive
Fred Drakef6669171998-05-06 19:52:49 +0000670operators:
671
Fred Drakecb4638a2001-07-06 22:49:53 +0000672\begin{productionlist}
673 \production{m_expr}
674 {\token{u_expr} | \token{m_expr} "*" \token{u_expr}
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000675 | \token{m_expr} "//" \token{u_expr}
Fred Drake53815882002-03-15 23:21:37 +0000676 | \token{m_expr} "/" \token{u_expr}}
677 \productioncont{| \token{m_expr} "\%" \token{u_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000678 \production{a_expr}
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000679 {\token{m_expr} | \token{a_expr} "+" \token{m_expr}
680 | \token{a_expr} "-" \token{m_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000681\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000682
Fred Drake5c07d9b1998-05-14 19:37:06 +0000683The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000684arguments. The arguments must either both be numbers, or one argument
Fred Drakec3b18d72000-12-07 04:54:02 +0000685must be an integer (plain or long) and the other must be a sequence.
686In the former case, the numbers are converted to a common type and
687then multiplied together. In the latter case, sequence repetition is
Fred Drakef6669171998-05-06 19:52:49 +0000688performed; a negative repetition factor yields an empty sequence.
689\index{multiplication}
690
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000691The \code{/} (division) and \code{//} (floor division) operators yield
692the quotient of their arguments. The numeric arguments are first
693converted to a common type. Plain or long integer division yields an
694integer of the same type; the result is that of mathematical division
695with the `floor' function applied to the result. Division by zero
696raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000697\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000698\exindex{ZeroDivisionError}
699\index{division}
700
Fred Drake5c07d9b1998-05-14 19:37:06 +0000701The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000702division of the first argument by the second. The numeric arguments
703are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000704the \exception{ZeroDivisionError} exception. The arguments may be floating
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000705point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000706\code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
707yields a result with the same sign as its second operand (or zero);
Tim Peters5b21df42002-11-24 20:23:04 +0000708the absolute value of the result is strictly smaller than the absolute
709value of the second operand\footnote{
Gustavo Niemeyerf9554122002-11-26 18:14:35 +0000710 While \code{abs(x\%y) < abs(y)} is true mathematically, for
Tim Peters5b21df42002-11-24 20:23:04 +0000711 floats it may not be true numerically due to roundoff. For
712 example, and assuming a platform on which a Python float is an
713 IEEE 754 double-precision number, in order that \code{-1e-100 \% 1e100}
714 have the same sign as \code{1e100}, the computed result is
715 \code{-1e-100 + 1e100}, which is numerically exactly equal
716 to \code{1e100}. Function \function{fmod()} in the \module{math}
717 module returns a result whose sign matches the sign of the
718 first argument instead, and so returns \code{-1e-100} in this case.
719 Which approach is more appropriate depends on the application.
720}.
Fred Drakef6669171998-05-06 19:52:49 +0000721\index{modulo}
722
723The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000724following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
725modulo are also connected with the built-in function \function{divmod()}:
726\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Raymond Hettinger6cf09f02002-05-21 18:19:49 +0000727floating point numbers; there similar identities hold
Raymond Hettingerdaa34042003-06-26 17:41:40 +0000728approximately where \code{x/y} is replaced by \code{floor(x/y)} or
Tim Peters5b21df42002-11-24 20:23:04 +0000729\code{floor(x/y) - 1}\footnote{
Fred Drake1ea7c751999-05-06 14:46:35 +0000730 If x is very close to an exact integer multiple of y, it's
731 possible for \code{floor(x/y)} to be one larger than
732 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
733 the latter result, in order to preserve that \code{divmod(x,y)[0]
734 * y + x \%{} y} be very close to \code{x}.
Raymond Hettinger6cf09f02002-05-21 18:19:49 +0000735}.
736
Georg Brandlc47f1c12005-12-26 23:15:48 +0000737In addition to performing the modulo operation on numbers, the \code{\%}
738operator is also overloaded by string and unicode objects to perform
739string formatting (also known as interpolation). The syntax for string
Georg Brandl5f0ff5c2006-01-20 17:51:37 +0000740formatting is described in the
741\citetitle[../lib/typesseq-strings.html]{Python Library Reference},
742section ``Sequence Types''.
Georg Brandlc47f1c12005-12-26 23:15:48 +0000743
Raymond Hettinger463bfaf2002-10-11 21:08:02 +0000744\deprecated{2.3}{The floor division operator, the modulo operator,
745and the \function{divmod()} function are no longer defined for complex
746numbers. Instead, convert to a floating point number using the
747\function{abs()} function if appropriate.}
Fred Drakef6669171998-05-06 19:52:49 +0000748
Fred Drake5c07d9b1998-05-14 19:37:06 +0000749The \code{+} (addition) operator yields the sum of its arguments.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000750The arguments must either both be numbers or both sequences of the
Fred Drakef6669171998-05-06 19:52:49 +0000751same type. In the former case, the numbers are converted to a common
752type and then added together. In the latter case, the sequences are
753concatenated.
754\index{addition}
755
Fred Drake5c07d9b1998-05-14 19:37:06 +0000756The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000757arguments. The numeric arguments are first converted to a common
758type.
759\index{subtraction}
760
Fred Drake2829f1c2001-06-23 05:27:20 +0000761
Fred Drake020f8c01998-07-28 19:32:59 +0000762\section{Shifting operations\label{shifting}}
Fred Drakef6669171998-05-06 19:52:49 +0000763\indexii{shifting}{operation}
764
765The shifting operations have lower priority than the arithmetic
766operations:
767
Fred Drakecb4638a2001-07-06 22:49:53 +0000768\begin{productionlist}
Fred Drake2269d862004-11-11 06:14:05 +0000769 % The empty groups below prevent conversion to guillemets.
Fred Drakecb4638a2001-07-06 22:49:53 +0000770 \production{shift_expr}
771 {\token{a_expr}
Fred Drake2269d862004-11-11 06:14:05 +0000772 | \token{shift_expr} ( "<{}<" | ">{}>" ) \token{a_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000773\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000774
775These operators accept plain or long integers as arguments. The
776arguments are converted to a common type. They shift the first
777argument to the left or right by the number of bits given by the
778second argument.
779
780A right shift by \var{n} bits is defined as division by
781\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
782multiplication with \code{pow(2,\var{n})}; for plain integers there is
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000783no overflow check so in that case the operation drops bits and flips
784the sign if the result is not less than \code{pow(2,31)} in absolute
785value. Negative shift counts raise a \exception{ValueError}
786exception.
Fred Drakef6669171998-05-06 19:52:49 +0000787\exindex{ValueError}
788
Fred Drake2829f1c2001-06-23 05:27:20 +0000789
Fred Drake020f8c01998-07-28 19:32:59 +0000790\section{Binary bit-wise operations\label{bitwise}}
Fred Drakef6669171998-05-06 19:52:49 +0000791\indexiii{binary}{bit-wise}{operation}
792
793Each of the three bitwise operations has a different priority level:
794
Fred Drakecb4638a2001-07-06 22:49:53 +0000795\begin{productionlist}
796 \production{and_expr}
797 {\token{shift_expr} | \token{and_expr} "\&" \token{shift_expr}}
798 \production{xor_expr}
799 {\token{and_expr} | \token{xor_expr} "\textasciicircum" \token{and_expr}}
800 \production{or_expr}
801 {\token{xor_expr} | \token{or_expr} "|" \token{xor_expr}}
802\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000803
Fred Drake5c07d9b1998-05-14 19:37:06 +0000804The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000805must be plain or long integers. The arguments are converted to a
806common type.
807\indexii{bit-wise}{and}
808
Fred Drake5c07d9b1998-05-14 19:37:06 +0000809The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000810arguments, which must be plain or long integers. The arguments are
811converted to a common type.
812\indexii{bit-wise}{xor}
813\indexii{exclusive}{or}
814
Fred Drake5c07d9b1998-05-14 19:37:06 +0000815The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000816arguments, which must be plain or long integers. The arguments are
817converted to a common type.
818\indexii{bit-wise}{or}
819\indexii{inclusive}{or}
820
Fred Drake2829f1c2001-06-23 05:27:20 +0000821
Fred Drake020f8c01998-07-28 19:32:59 +0000822\section{Comparisons\label{comparisons}}
Fred Drakef6669171998-05-06 19:52:49 +0000823\index{comparison}
824
Fred Drake1156f622000-09-19 18:10:05 +0000825Unlike C, all comparison operations in Python have the same priority,
826which is lower than that of any arithmetic, shifting or bitwise
827operation. Also unlike C, expressions like \code{a < b < c} have the
828interpretation that is conventional in mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000829\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000830
Fred Drakecb4638a2001-07-06 22:49:53 +0000831\begin{productionlist}
832 \production{comparison}
833 {\token{or_expr} ( \token{comp_operator} \token{or_expr} )*}
834 \production{comp_operator}
Fred Drake53815882002-03-15 23:21:37 +0000835 {"<" | ">" | "==" | ">=" | "<=" | "<>" | "!="}
836 \productioncont{| "is" ["not"] | ["not"] "in"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000837\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000838
Raymond Hettingerb268f032003-06-06 02:52:14 +0000839Comparisons yield boolean values: \code{True} or \code{False}.
Fred Drakef6669171998-05-06 19:52:49 +0000840
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000841Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
Fred Drakef6669171998-05-06 19:52:49 +0000842equivalent to \code{x < y and y <= z}, except that \code{y} is
843evaluated only once (but in both cases \code{z} is not evaluated at all
844when \code{x < y} is found to be false).
845\indexii{chaining}{comparisons}
846
847Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
848expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
849operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000850to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
Fred Drakef6669171998-05-06 19:52:49 +0000851\var{y opy z}, except that each expression is evaluated at most once.
852
853Note that \var{a opa b opb c} doesn't imply any kind of comparison
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000854between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
Fred Drakef6669171998-05-06 19:52:49 +0000855perfectly legal (though perhaps not pretty).
856
Fred Drake5c07d9b1998-05-14 19:37:06 +0000857The forms \code{<>} and \code{!=} are equivalent; for consistency with
858C, \code{!=} is preferred; where \code{!=} is mentioned below
Fred Drake1156f622000-09-19 18:10:05 +0000859\code{<>} is also accepted. The \code{<>} spelling is considered
860obsolescent.
Fred Drakef6669171998-05-06 19:52:49 +0000861
Fred Drake1156f622000-09-19 18:10:05 +0000862The operators \code{<}, \code{>}, \code{==}, \code{>=}, \code{<=}, and
863\code{!=} compare
864the values of two objects. The objects need not have the same type.
Fred Drakefd867712002-04-09 14:39:10 +0000865If both are numbers, they are converted to a common type. Otherwise,
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000866objects of different types \emph{always} compare unequal, and are
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000867ordered consistently but arbitrarily. You can control comparison
868behavior of objects of non-builtin types by defining a \code{__cmp__}
869method or rich comparison methods like \code{__gt__}, described in
870section~\ref{specialnames}.
Fred Drakef6669171998-05-06 19:52:49 +0000871
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000872(This unusual definition of comparison was used to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000873definition of operations like sorting and the \keyword{in} and
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000874\keyword{not in} operators. In the future, the comparison rules for
875objects of different types are likely to change.)
Fred Drakef6669171998-05-06 19:52:49 +0000876
877Comparison of objects of the same type depends on the type:
878
879\begin{itemize}
880
881\item
882Numbers are compared arithmetically.
883
884\item
885Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +0000886(the result of the built-in function \function{ord()}) of their
Fred Drake1156f622000-09-19 18:10:05 +0000887characters. Unicode and 8-bit strings are fully interoperable in this
888behavior.
Fred Drakef6669171998-05-06 19:52:49 +0000889
890\item
891Tuples and lists are compared lexicographically using comparison of
Raymond Hettingerdaa34042003-06-26 17:41:40 +0000892corresponding elements. This means that to compare equal, each
893element must compare equal and the two sequences must be of the same
894type and have the same length.
895
896If not equal, the sequences are ordered the same as their first
897differing elements. For example, \code{cmp([1,2,x], [1,2,y])} returns
898the same as \code{cmp(x,y)}. If the corresponding element does not
899exist, the shorter sequence is ordered first (for example,
900\code{[1,2] < [1,2,3]}).
Fred Drakef6669171998-05-06 19:52:49 +0000901
902\item
Tim Peters20524db2001-10-01 20:22:45 +0000903Mappings (dictionaries) compare equal if and only if their sorted
904(key, value) lists compare equal.\footnote{The implementation computes
905 this efficiently, without constructing lists or sorting.}
906Outcomes other than equality are resolved consistently, but are not
Tim Peters1350c072001-10-01 20:25:26 +0000907otherwise defined.\footnote{Earlier versions of Python used
Tim Peters20524db2001-10-01 20:22:45 +0000908 lexicographic comparison of the sorted (key, value) lists, but this
909 was very expensive for the common case of comparing for equality. An
910 even earlier version of Python compared dictionaries by identity only,
911 but this caused surprises because people expected to be able to test
912 a dictionary for emptiness by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +0000913
914\item
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000915Most other objects of builtin types compare unequal unless they are
916the same object;
Fred Drakef6669171998-05-06 19:52:49 +0000917the choice whether one object is considered smaller or larger than
918another one is made arbitrarily but consistently within one
919execution of a program.
920
921\end{itemize}
922
Fred Drake7399b9e2000-07-11 19:43:47 +0000923The operators \keyword{in} and \keyword{not in} test for set
Fred Drakeac79e952001-03-06 07:32:11 +0000924membership. \code{\var{x} in \var{s}} evaluates to true if \var{x}
925is a member of the set \var{s}, and false otherwise. \code{\var{x}
926not in \var{s}} returns the negation of \code{\var{x} in \var{s}}.
927The set membership test has traditionally been bound to sequences; an
928object is a member of a set if the set is a sequence and contains an
929element equal to that object. However, it is possible for an object
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +0000930to support membership tests without being a sequence. In particular,
Fred Drakeb184ae82005-01-19 03:39:17 +0000931dictionaries support membership testing as a nicer way of spelling
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +0000932\code{\var{key} in \var{dict}}; other mapping types may follow suit.
Fred Drake7399b9e2000-07-11 19:43:47 +0000933
Fred Drake34bafcc2001-01-14 02:57:14 +0000934For the list and tuple types, \code{\var{x} in \var{y}} is true if and
Fred Drakeac79e952001-03-06 07:32:11 +0000935only if there exists an index \var{i} such that
Fred Drake34bafcc2001-01-14 02:57:14 +0000936\code{\var{x} == \var{y}[\var{i}]} is true.
Fred Drake7399b9e2000-07-11 19:43:47 +0000937
Fred Drake1156f622000-09-19 18:10:05 +0000938For the Unicode and string types, \code{\var{x} in \var{y}} is true if
Raymond Hettingerd0cda1d2003-06-26 19:32:10 +0000939and only if \var{x} is a substring of \var{y}. An equivalent test is
940\code{y.find(x) != -1}. Note, \var{x} and \var{y} need not be the
941same type; consequently, \code{u'ab' in 'abc'} will return \code{True}.
942Empty strings are always considered to be a substring of any other string,
943so \code{"" in "abc"} will return \code{True}.
944\versionchanged[Previously, \var{x} was required to be a string of
945length \code{1}]{2.3}
Fred Drake7399b9e2000-07-11 19:43:47 +0000946
947For user-defined classes which define the \method{__contains__()} method,
948\code{\var{x} in \var{y}} is true if and only if
949\code{\var{y}.__contains__(\var{x})} is true.
950
951For user-defined classes which do not define \method{__contains__()} and
Fred Drake1156f622000-09-19 18:10:05 +0000952do define \method{__getitem__()}, \code{\var{x} in \var{y}} is true if
953and only if there is a non-negative integer index \var{i} such that
Fred Drake7399b9e2000-07-11 19:43:47 +0000954\code{\var{x} == \var{y}[\var{i}]}, and all lower integer indices
955do not raise \exception{IndexError} exception. (If any other exception
956is raised, it is as if \keyword{in} raised that exception).
957
958The operator \keyword{not in} is defined to have the inverse true value
959of \keyword{in}.
Fred Drakef6669171998-05-06 19:52:49 +0000960\opindex{in}
961\opindex{not in}
962\indexii{membership}{test}
963\obindex{sequence}
964
Fred Drake5c07d9b1998-05-14 19:37:06 +0000965The operators \keyword{is} and \keyword{is not} test for object identity:
966\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
967are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +0000968truth value.
969\opindex{is}
970\opindex{is not}
971\indexii{identity}{test}
972
Fred Drake2829f1c2001-06-23 05:27:20 +0000973
Fred Drake020f8c01998-07-28 19:32:59 +0000974\section{Boolean operations\label{Booleans}}
Fred Drakef6669171998-05-06 19:52:49 +0000975\indexii{Boolean}{operation}
976
977Boolean operations have the lowest priority of all Python operations:
978
Fred Drakecb4638a2001-07-06 22:49:53 +0000979\begin{productionlist}
980 \production{expression}
Thomas Woutersdca3b9c2006-02-27 00:24:13 +0000981 {\token{or_test} [\token{if} \token{or_test} \token{else}
982 \token{test}] | \token{lambda_form}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000983 \production{or_test}
984 {\token{and_test} | \token{or_test} "or" \token{and_test}}
985 \production{and_test}
986 {\token{not_test} | \token{and_test} "and" \token{not_test}}
987 \production{not_test}
988 {\token{comparison} | "not" \token{not_test}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000989\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000990
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000991In the context of Boolean operations, and also when expressions are
Fred Drakef6669171998-05-06 19:52:49 +0000992used by control flow statements, the following values are interpreted
Georg Brandl6cd53772005-08-21 12:22:58 +0000993as false: \code{False}, \code{None}, numeric zero of all types, and empty
994strings and containers (including strings, tuples, lists, dictionaries,
995sets and frozensets). All other values are interpreted as true.
Fred Drakef6669171998-05-06 19:52:49 +0000996
Raymond Hettinger46a16f22004-04-23 17:11:47 +0000997The operator \keyword{not} yields \code{True} if its argument is false,
998\code{False} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +0000999\opindex{not}
1000
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001001The expression \code{\var{x} if \var{C} else \var{y}} first evaluates
1002\var{C} (\emph{not} \var{x}); if \var{C} is true, \var{x} is evaluated and
1003its value is returned; otherwise, \var{y} is evaluated and its value is
Neal Norwitzf9f61b42006-02-27 16:31:12 +00001004returned. \versionadded{2.5}
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001005
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001006The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +00001007\var{x} is false, its value is returned; otherwise, \var{y} is
1008evaluated and the resulting value is returned.
1009\opindex{and}
1010
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001011The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +00001012\var{x} is true, its value is returned; otherwise, \var{y} is
1013evaluated and the resulting value is returned.
1014\opindex{or}
1015
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001016(Note that neither \keyword{and} nor \keyword{or} restrict the value
Raymond Hettinger46a16f22004-04-23 17:11:47 +00001017and type they return to \code{False} and \code{True}, but rather return the
Fred Drake5c07d9b1998-05-14 19:37:06 +00001018last evaluated argument.
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001019This is sometimes useful, e.g., if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +00001020replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +00001021\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +00001022invent a value anyway, it does not bother to return a value of the
Raymond Hettinger46a16f22004-04-23 17:11:47 +00001023same type as its argument, so e.g., \code{not 'foo'} yields \code{False},
Fred Drake5c07d9b1998-05-14 19:37:06 +00001024not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +00001025
Jeremy Hylton2225add2002-04-01 21:05:21 +00001026\section{Lambdas\label{lambdas}}
1027\indexii{lambda}{expression}
1028\indexii{lambda}{form}
Martin v. Löwis95cf84a2003-10-19 07:32:24 +00001029\indexii{anonymous}{function}
Jeremy Hylton2225add2002-04-01 21:05:21 +00001030
Martin v. Löwis477c8562004-06-02 12:54:33 +00001031\begin{productionlist}
1032 \production{lambda_form}
1033 {"lambda" [\token{parameter_list}]: \token{expression}}
1034\end{productionlist}
1035
Fred Drakef6669171998-05-06 19:52:49 +00001036Lambda forms (lambda expressions) have the same syntactic position as
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001037expressions. They are a shorthand to create anonymous functions; the
1038expression \code{lambda \var{arguments}: \var{expression}}
Jeremy Hylton2225add2002-04-01 21:05:21 +00001039yields a function object. The unnamed object behaves like a function
Raymond Hettinger7fd9ced2002-06-25 04:04:14 +00001040object defined with
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001041
1042\begin{verbatim}
1043def name(arguments):
1044 return expression
1045\end{verbatim}
1046
1047See section \ref{function} for the syntax of parameter lists. Note
1048that functions created with lambda forms cannot contain statements.
Fred Drakef6669171998-05-06 19:52:49 +00001049\label{lambda}
Fred Drake88382692001-06-05 02:17:02 +00001050
Fred Drake020f8c01998-07-28 19:32:59 +00001051\section{Expression lists\label{exprlists}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001052\indexii{expression}{list}
Fred Drakef6669171998-05-06 19:52:49 +00001053
Fred Drakecb4638a2001-07-06 22:49:53 +00001054\begin{productionlist}
1055 \production{expression_list}
1056 {\token{expression} ( "," \token{expression} )* [","]}
1057\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +00001058
Fred Drakec009d192000-04-25 21:09:10 +00001059An expression list containing at least one comma yields a
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001060tuple. The length of the tuple is the number of expressions in the
1061list. The expressions are evaluated from left to right.
Fred Drakef6669171998-05-06 19:52:49 +00001062\obindex{tuple}
1063
1064The trailing comma is required only to create a single tuple (a.k.a. a
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001065\emph{singleton}); it is optional in all other cases. A single
Fred Drakec009d192000-04-25 21:09:10 +00001066expression without a trailing comma doesn't create a
1067tuple, but rather yields the value of that expression.
Fred Drakef6669171998-05-06 19:52:49 +00001068(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +00001069\code{()}.)
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001070\indexii{trailing}{comma}
Fred Drakef6669171998-05-06 19:52:49 +00001071
Gustavo Niemeyer78429a62002-12-16 13:54:02 +00001072\section{Evaluation order\label{evalorder}}
1073\indexii{evaluation}{order}
1074
1075Python evaluates expressions from left to right. Notice that while
1076evaluating an assignment, the right-hand side is evaluated before
1077the left-hand side.
1078
1079In the following lines, expressions will be evaluated in the
1080arithmetic order of their suffixes:
1081
1082\begin{verbatim}
1083expr1, expr2, expr3, expr4
1084(expr1, expr2, expr3, expr4)
1085{expr1: expr2, expr3: expr4}
1086expr1 + expr2 * (expr3 - expr4)
1087func(expr1, expr2, *expr3, **expr4)
1088expr3, expr4 = expr1, expr2
1089\end{verbatim}
Fred Draked09120b1999-04-29 16:43:42 +00001090
Fred Drake020f8c01998-07-28 19:32:59 +00001091\section{Summary\label{summary}}
Fred Drakef6669171998-05-06 19:52:49 +00001092
Fred Draked09120b1999-04-29 16:43:42 +00001093The following table summarizes the operator
1094precedences\indexii{operator}{precedence} in Python, from lowest
1095precedence (least binding) to highest precedence (most binding).
1096Operators in the same box have the same precedence. Unless the syntax
1097is explicitly given, operators are binary. Operators in the same box
Alex Martellic516b0e2003-11-09 16:33:56 +00001098group left to right (except for comparisons, including tests, which all
1099have the same precedence and chain from left to right --- see section
1100\ref{comparisons} -- and exponentiation, which groups from right to left).
Fred Drakef6669171998-05-06 19:52:49 +00001101
Fred Draked09120b1999-04-29 16:43:42 +00001102\begin{tableii}{c|l}{textrm}{Operator}{Description}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001103 \lineii{\keyword{lambda}} {Lambda expression}
1104 \hline
1105 \lineii{\keyword{or}} {Boolean OR}
1106 \hline
1107 \lineii{\keyword{and}} {Boolean AND}
1108 \hline
1109 \lineii{\keyword{not} \var{x}} {Boolean NOT}
1110 \hline
1111 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
1112 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
1113 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
Fred Drake9beee801998-10-21 00:44:49 +00001114 \code{<>}, \code{!=}, \code{==}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001115 {Comparisons}
1116 \hline
1117 \lineii{\code{|}} {Bitwise OR}
1118 \hline
1119 \lineii{\code{\^}} {Bitwise XOR}
1120 \hline
1121 \lineii{\code{\&}} {Bitwise AND}
1122 \hline
Thomas Wouters477c8d52006-05-27 19:21:47 +00001123 \lineii{\code{<<}, \code{>>}} {Shifts}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001124 \hline
1125 \lineii{\code{+}, \code{-}}{Addition and subtraction}
1126 \hline
Fred Drake9beee801998-10-21 00:44:49 +00001127 \lineii{\code{*}, \code{/}, \code{\%}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001128 {Multiplication, division, remainder}
1129 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001130 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
1131 \lineii{\code{\~\var{x}}} {Bitwise not}
1132 \hline
Fred Drakeb8ac0092001-05-09 16:51:49 +00001133 \lineii{\code{**}} {Exponentiation}
1134 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001135 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
1136 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
1137 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
1138 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
Fred Draked09120b1999-04-29 16:43:42 +00001139 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001140 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
1141 \lineii{\code{[\var{expressions}\ldots]}} {List display}
1142 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
1143 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
1144\end{tableii}