blob: fb8e3ddb9a3c4075aca12be2f196781ae70ffd4d [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
66An identifier occurring as an atom is a reference to a local, global
67or built-in name binding. If a name is assigned to anywhere in a code
68block (even in unreachable code), and is not mentioned in a
Fred Drake5c07d9b1998-05-14 19:37:06 +000069\keyword{global} statement in that code block, then it refers to a local
Fred Drakef6669171998-05-06 19:52:49 +000070name throughout that code block. When it is not assigned to anywhere
71in the block, or when it is assigned to but also explicitly listed in
Fred Drake5c07d9b1998-05-14 19:37:06 +000072a \keyword{global} statement, it refers to a global name if one exists,
Fred Drakeac79e952001-03-06 07:32:11 +000073else to a built-in name (and this binding may dynamically
74change).\footnote{The Python interpreter provides a useful set of
75 predefined built-in functions. It is not recommended to reuse
76 (hide) these names with self defined objects. See the
77 \citetitle[../lib/built-in-funcs.html]{Python Library Reference} for
78 the descriptions of built-in functions and methods.}
Fred Drakef6669171998-05-06 19:52:49 +000079\indexii{name}{binding}
80\index{code block}
81\stindex{global}
82\indexii{built-in}{name}
83\indexii{global}{name}
84
85When the name is bound to an object, evaluation of the atom yields
86that object. When a name is not bound, an attempt to evaluate it
Fred Drake5c07d9b1998-05-14 19:37:06 +000087raises a \exception{NameError} exception.
Fred Drakef6669171998-05-06 19:52:49 +000088\exindex{NameError}
89
Guido van Rossum3a0ad601998-07-23 21:57:42 +000090\strong{Private name mangling:}%
91\indexii{name}{mangling}%
92\indexii{private}{names}%
93when an identifier that textually occurs in a class definition begins
94with two or more underscore characters and does not end in two or more
Fred Drakeea81edf1998-11-25 17:51:15 +000095underscores, it is considered a \dfn{private name} of that class.
Guido van Rossum3a0ad601998-07-23 21:57:42 +000096Private names are transformed to a longer form before code is
97generated for them. The transformation inserts the class name in
98front of the name, with leading underscores removed, and a single
99underscore inserted in front of the class name. For example, the
100identifier \code{__spam} occurring in a class named \code{Ham} will be
101transformed to \code{_Ham__spam}. This transformation is independent
102of the syntactical context in which the identifier is used. If the
103transformed name is extremely long (longer than 255 characters),
104implementation defined truncation may happen. If the class name
105consists only of underscores, no transformation is done.
106
Fred Drake2829f1c2001-06-23 05:27:20 +0000107
Fred Drake020f8c01998-07-28 19:32:59 +0000108\subsection{Literals\label{atom-literals}}
Fred Drakef6669171998-05-06 19:52:49 +0000109\index{literal}
110
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000111Python supports string literals and various numeric literals:
Fred Drakef6669171998-05-06 19:52:49 +0000112
Fred Drakecb4638a2001-07-06 22:49:53 +0000113\begin{productionlist}
114 \production{literal}
Fred Drake53815882002-03-15 23:21:37 +0000115 {\token{stringliteral} | \token{integer} | \token{longinteger}}
116 \productioncont{| \token{floatnumber} | \token{imagnumber}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000117\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000118
119Evaluation of a literal yields an object of the given type (string,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000120integer, long integer, floating point number, complex number) with the
121given value. The value may be approximated in the case of floating
122point and imaginary (complex) literals. See section \ref{literals}
123for details.
Fred Drakef6669171998-05-06 19:52:49 +0000124
125All literals correspond to immutable data types, and hence the
126object's identity is less important than its value. Multiple
127evaluations of literals with the same value (either the same
128occurrence in the program text or a different occurrence) may obtain
129the same object or a different object with the same value.
130\indexiii{immutable}{data}{type}
Fred Drakee15956b2000-04-03 04:51:13 +0000131\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000132
Fred Drake2829f1c2001-06-23 05:27:20 +0000133
Fred Drake020f8c01998-07-28 19:32:59 +0000134\subsection{Parenthesized forms\label{parenthesized}}
Fred Drakef6669171998-05-06 19:52:49 +0000135\index{parenthesized form}
136
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000137A parenthesized form is an optional expression list enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000138parentheses:
139
Fred Drakecb4638a2001-07-06 22:49:53 +0000140\begin{productionlist}
141 \production{parenth_form}
142 {"(" [\token{expression_list}] ")"}
143\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000144
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000145A parenthesized expression list yields whatever that expression list
146yields: if the list contains at least one comma, it yields a tuple;
147otherwise, it yields the single expression that makes up the
148expression list.
Fred Drakef6669171998-05-06 19:52:49 +0000149
150An empty pair of parentheses yields an empty tuple object. Since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000151tuples are immutable, the rules for literals apply (i.e., two
152occurrences of the empty tuple may or may not yield the same object).
Fred Drakef6669171998-05-06 19:52:49 +0000153\indexii{empty}{tuple}
154
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000155Note that tuples are not formed by the parentheses, but rather by use
Fred Drakef6669171998-05-06 19:52:49 +0000156of the comma operator. The exception is the empty tuple, for which
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000157parentheses \emph{are} required --- allowing unparenthesized ``nothing''
Fred Drakef6669171998-05-06 19:52:49 +0000158in expressions would cause ambiguities and allow common typos to
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000159pass uncaught.
Fred Drakef6669171998-05-06 19:52:49 +0000160\index{comma}
161\indexii{tuple}{display}
162
Fred Drake2829f1c2001-06-23 05:27:20 +0000163
Fred Drake020f8c01998-07-28 19:32:59 +0000164\subsection{List displays\label{lists}}
Fred Drakef6669171998-05-06 19:52:49 +0000165\indexii{list}{display}
Skip Montanarob6559392000-09-11 16:31:55 +0000166\indexii{list}{comprehensions}
Fred Drakef6669171998-05-06 19:52:49 +0000167
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000168A list display is a possibly empty series of expressions enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000169square brackets:
170
Fred Drakecb4638a2001-07-06 22:49:53 +0000171\begin{productionlist}
172 \production{list_display}
173 {"[" [\token{listmaker}] "]"}
174 \production{listmaker}
175 {\token{expression} ( \token{list_for}
176 | ( "," \token{expression})* [","] )}
177 \production{list_iter}
178 {\token{list_for} | \token{list_if}}
179 \production{list_for}
180 {"for" \token{expression_list} "in" \token{testlist}
181 [\token{list_iter}]}
182 \production{list_if}
183 {"if" \token{test} [\token{list_iter}]}
184\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000185
Skip Montanaro803d6e52000-08-12 18:09:51 +0000186A list display yields a new list object. Its contents are specified
187by providing either a list of expressions or a list comprehension.
Skip Montanarob6559392000-09-11 16:31:55 +0000188\indexii{list}{comprehensions}
Skip Montanaro803d6e52000-08-12 18:09:51 +0000189When a comma-separated list of expressions is supplied, its elements are
190evaluated from left to right and placed into the list object in that
191order. When a list comprehension is supplied, it consists of a
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000192single expression followed by at least one \keyword{for} clause and zero or
Tim Peters20524db2001-10-01 20:22:45 +0000193more \keyword{for} or \keyword{if} clauses. In this
Skip Montanaro803d6e52000-08-12 18:09:51 +0000194case, the elements of the new list are those that would be produced
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000195by considering each of the \keyword{for} or \keyword{if} clauses a block,
Tim Peters20524db2001-10-01 20:22:45 +0000196nesting from
Skip Montanaro803d6e52000-08-12 18:09:51 +0000197left to right, and evaluating the expression to produce a list element
198each time the innermost block is reached.
Fred Drakef6669171998-05-06 19:52:49 +0000199\obindex{list}
Fred Drakef6669171998-05-06 19:52:49 +0000200\indexii{empty}{list}
201
Fred Drake2829f1c2001-06-23 05:27:20 +0000202
Fred Drake020f8c01998-07-28 19:32:59 +0000203\subsection{Dictionary displays\label{dict}}
Fred Drakef6669171998-05-06 19:52:49 +0000204\indexii{dictionary}{display}
205
206A dictionary display is a possibly empty series of key/datum pairs
207enclosed in curly braces:
208\index{key}
209\index{datum}
210\index{key/datum pair}
211
Fred Drakecb4638a2001-07-06 22:49:53 +0000212\begin{productionlist}
213 \production{dict_display}
Fred Drake83d14c12002-03-16 06:35:54 +0000214 {"\{" [\token{key_datum_list}] "\}"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000215 \production{key_datum_list}
216 {\token{key_datum} ("," \token{key_datum})* [","]}
217 \production{key_datum}
218 {\token{expression} ":" \token{expression}}
219\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000220
221A dictionary display yields a new dictionary object.
222\obindex{dictionary}
223
224The key/datum pairs are evaluated from left to right to define the
225entries of the dictionary: each key object is used as a key into the
226dictionary to store the corresponding datum.
227
228Restrictions on the types of the key values are listed earlier in
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000229section \ref{types}. (To summarize,the key type should be hashable,
230which excludes all mutable objects.) Clashes between duplicate keys
231are not detected; the last datum (textually rightmost in the display)
232stored for a given key value prevails.
Fred Drakee15956b2000-04-03 04:51:13 +0000233\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000234
Fred Drake2829f1c2001-06-23 05:27:20 +0000235
Fred Drake020f8c01998-07-28 19:32:59 +0000236\subsection{String conversions\label{string-conversions}}
Fred Drakef6669171998-05-06 19:52:49 +0000237\indexii{string}{conversion}
238\indexii{reverse}{quotes}
239\indexii{backward}{quotes}
240\index{back-quotes}
241
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000242A string conversion is an expression list enclosed in reverse (a.k.a.
Fred Drakef6669171998-05-06 19:52:49 +0000243backward) quotes:
244
Fred Drakecb4638a2001-07-06 22:49:53 +0000245\begin{productionlist}
246 \production{string_conversion}
247 {"`" \token{expression_list} "`"}
248\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000249
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000250A string conversion evaluates the contained expression list and
Fred Drakef6669171998-05-06 19:52:49 +0000251converts the resulting object into a string according to rules
252specific to its type.
253
Fred Drake5c07d9b1998-05-14 19:37:06 +0000254If the object is a string, a number, \code{None}, or a tuple, list or
Fred Drakef6669171998-05-06 19:52:49 +0000255dictionary containing only objects whose type is one of these, the
256resulting string is a valid Python expression which can be passed to
Fred Drake5c07d9b1998-05-14 19:37:06 +0000257the built-in function \function{eval()} to yield an expression with the
Fred Drakef6669171998-05-06 19:52:49 +0000258same value (or an approximation, if floating point numbers are
259involved).
260
261(In particular, converting a string adds quotes around it and converts
262``funny'' characters to escape sequences that are safe to print.)
263
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000264It is illegal to attempt to convert recursive objects (e.g., lists or
Fred Drakef6669171998-05-06 19:52:49 +0000265dictionaries that contain a reference to themselves, directly or
266indirectly.)
267\obindex{recursive}
268
Fred Drake5c07d9b1998-05-14 19:37:06 +0000269The built-in function \function{repr()} performs exactly the same
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000270conversion in its argument as enclosing it in parentheses and reverse
271quotes does. The built-in function \function{str()} performs a
272similar but more user-friendly conversion.
Fred Drakef6669171998-05-06 19:52:49 +0000273\bifuncindex{repr}
274\bifuncindex{str}
275
Fred Drake2829f1c2001-06-23 05:27:20 +0000276
Fred Drake020f8c01998-07-28 19:32:59 +0000277\section{Primaries\label{primaries}}
Fred Drakef6669171998-05-06 19:52:49 +0000278\index{primary}
279
280Primaries represent the most tightly bound operations of the language.
281Their syntax is:
282
Fred Drakecb4638a2001-07-06 22:49:53 +0000283\begin{productionlist}
284 \production{primary}
285 {\token{atom} | \token{attributeref}
286 | \token{subscription} | \token{slicing} | \token{call}}
287\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000288
Fred Drake2829f1c2001-06-23 05:27:20 +0000289
Fred Drake020f8c01998-07-28 19:32:59 +0000290\subsection{Attribute references\label{attribute-references}}
Fred Drakef6669171998-05-06 19:52:49 +0000291\indexii{attribute}{reference}
292
293An attribute reference is a primary followed by a period and a name:
294
Fred Drakecb4638a2001-07-06 22:49:53 +0000295\begin{productionlist}
296 \production{attributeref}
297 {\token{primary} "." \token{identifier}}
298\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000299
300The primary must evaluate to an object of a type that supports
Fred Drake34bafcc2001-01-14 02:57:14 +0000301attribute references, e.g., a module, list, or an instance. This
302object is then asked to produce the attribute whose name is the
303identifier. If this attribute is not available, the exception
Fred Drake5c07d9b1998-05-14 19:37:06 +0000304\exception{AttributeError}\exindex{AttributeError} is raised.
305Otherwise, the type and value of the object produced is determined by
306the object. Multiple evaluations of the same attribute reference may
307yield different objects.
Fred Drakef6669171998-05-06 19:52:49 +0000308\obindex{module}
309\obindex{list}
310
Fred Drake2829f1c2001-06-23 05:27:20 +0000311
Fred Drake020f8c01998-07-28 19:32:59 +0000312\subsection{Subscriptions\label{subscriptions}}
Fred Drakef6669171998-05-06 19:52:49 +0000313\index{subscription}
314
315A subscription selects an item of a sequence (string, tuple or list)
316or mapping (dictionary) object:
317\obindex{sequence}
318\obindex{mapping}
319\obindex{string}
320\obindex{tuple}
321\obindex{list}
322\obindex{dictionary}
323\indexii{sequence}{item}
324
Fred Drakecb4638a2001-07-06 22:49:53 +0000325\begin{productionlist}
326 \production{subscription}
327 {\token{primary} "[" \token{expression_list} "]"}
328\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000329
330The primary must evaluate to an object of a sequence or mapping type.
331
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000332If the primary is a mapping, the expression list must evaluate to an
333object whose value is one of the keys of the mapping, and the
334subscription selects the value in the mapping that corresponds to that
335key. (The expression list is a tuple except if it has exactly one
336item.)
Fred Drakef6669171998-05-06 19:52:49 +0000337
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000338If the primary is a sequence, the expression (list) must evaluate to a
339plain integer. If this value is negative, the length of the sequence
340is added to it (so that, e.g., \code{x[-1]} selects the last item of
341\code{x}.) The resulting value must be a nonnegative integer less
342than the number of items in the sequence, and the subscription selects
343the item whose index is that value (counting from zero).
Fred Drakef6669171998-05-06 19:52:49 +0000344
345A string's items are characters. A character is not a separate data
346type but a string of exactly one character.
347\index{character}
348\indexii{string}{item}
349
Fred Drake2829f1c2001-06-23 05:27:20 +0000350
Fred Drake020f8c01998-07-28 19:32:59 +0000351\subsection{Slicings\label{slicings}}
Fred Drakef6669171998-05-06 19:52:49 +0000352\index{slicing}
353\index{slice}
354
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000355A slicing selects a range of items in a sequence object (e.g., a
356string, tuple or list). Slicings may be used as expressions or as
357targets in assignment or del statements. The syntax for a slicing:
Fred Drakef6669171998-05-06 19:52:49 +0000358\obindex{sequence}
359\obindex{string}
360\obindex{tuple}
361\obindex{list}
362
Fred Drakecb4638a2001-07-06 22:49:53 +0000363\begin{productionlist}
364 \production{slicing}
365 {\token{simple_slicing} | \token{extended_slicing}}
366 \production{simple_slicing}
367 {\token{primary} "[" \token{short_slice} "]"}
368 \production{extended_slicing}
369 {\token{primary} "[" \token{slice_list} "]" }
370 \production{slice_list}
371 {\token{slice_item} ("," \token{slice_item})* [","]}
372 \production{slice_item}
373 {\token{expression} | \token{proper_slice} | \token{ellipsis}}
374 \production{proper_slice}
375 {\token{short_slice} | \token{long_slice}}
376 \production{short_slice}
377 {[\token{lower_bound}] ":" [\token{upper_bound}]}
378 \production{long_slice}
379 {\token{short_slice} ":" [\token{stride}]}
380 \production{lower_bound}
381 {\token{expression}}
382 \production{upper_bound}
383 {\token{expression}}
384 \production{stride}
385 {\token{expression}}
386 \production{ellipsis}
387 {"..."}
388\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000389
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000390There is ambiguity in the formal syntax here: anything that looks like
391an expression list also looks like a slice list, so any subscription
392can be interpreted as a slicing. Rather than further complicating the
393syntax, this is disambiguated by defining that in this case the
394interpretation as a subscription takes priority over the
395interpretation as a slicing (this is the case if the slice list
396contains no proper slice nor ellipses). Similarly, when the slice
397list has exactly one short slice and no trailing comma, the
398interpretation as a simple slicing takes priority over that as an
399extended slicing.\indexii{extended}{slicing}
400
401The semantics for a simple slicing are as follows. The primary must
402evaluate to a sequence object. The lower and upper bound expressions,
403if present, must evaluate to plain integers; defaults are zero and the
Fred Drakee15956b2000-04-03 04:51:13 +0000404\code{sys.maxint}, respectively. If either bound is negative, the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000405sequence's length is added to it. The slicing now selects all items
406with index \var{k} such that
Fred Drakef6669171998-05-06 19:52:49 +0000407\code{\var{i} <= \var{k} < \var{j}} where \var{i}
408and \var{j} are the specified lower and upper bounds. This may be an
409empty sequence. It is not an error if \var{i} or \var{j} lie outside the
410range of valid indexes (such items don't exist so they aren't
411selected).
412
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000413The semantics for an extended slicing are as follows. The primary
414must evaluate to a mapping object, and it is indexed with a key that
415is constructed from the slice list, as follows. If the slice list
416contains at least one comma, the key is a tuple containing the
417conversion of the slice items; otherwise, the conversion of the lone
418slice item is the key. The conversion of a slice item that is an
419expression is that expression. The conversion of an ellipsis slice
420item is the built-in \code{Ellipsis} object. The conversion of a
421proper slice is a slice object (see section \ref{types}) whose
Fred Drakeea81edf1998-11-25 17:51:15 +0000422\member{start}, \member{stop} and \member{step} attributes are the
423values of the expressions given as lower bound, upper bound and
424stride, respectively, substituting \code{None} for missing
425expressions.
Fred Drake99cd5731999-02-12 20:40:09 +0000426\withsubitem{(slice object attribute)}{\ttindex{start}
427 \ttindex{stop}\ttindex{step}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000428
Fred Drake2829f1c2001-06-23 05:27:20 +0000429
Fred Drake020f8c01998-07-28 19:32:59 +0000430\subsection{Calls\label{calls}}
Fred Drakef6669171998-05-06 19:52:49 +0000431\index{call}
432
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000433A call calls a callable object (e.g., a function) with a possibly empty
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000434series of arguments:
Fred Drakef6669171998-05-06 19:52:49 +0000435\obindex{callable}
436
Fred Drakecb4638a2001-07-06 22:49:53 +0000437\begin{productionlist}
438 \production{call}
439 {\token{primary} "(" [\token{argument_list} [","]] ")"}
440 \production{argument_list}
Fred Drake53815882002-03-15 23:21:37 +0000441 {\token{positional_arguments} ["," \token{keyword_arguments}}
442 \productioncont{ ["," "*" \token{expression} ["," "**" \token{expression}]]]}
443 \productioncont{| \token{keyword_arguments} ["," "*" \token{expression}}
444 \productioncont{ ["," "**" \token{expression}]]}
445 \productioncont{| "*" \token{expression} ["," "**" \token{expression}]}
446 \productioncont{| "**" \token{expression}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000447 \production{positional_arguments}
448 {\token{expression} ("," \token{expression})*}
449 \production{keyword_arguments}
450 {\token{keyword_item} ("," \token{keyword_item})*}
451 \production{keyword_item}
452 {\token{identifier} "=" \token{expression}}
453\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000454
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000455A trailing comma may be present after an argument list but does not
456affect the semantics.
457
Fred Drakef6669171998-05-06 19:52:49 +0000458The primary must evaluate to a callable object (user-defined
459functions, built-in functions, methods of built-in objects, class
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000460objects, methods of class instances, and certain class instances
461themselves are callable; extensions may define additional callable
462object types). All argument expressions are evaluated before the call
463is attempted. Please refer to section \ref{function} for the syntax
464of formal parameter lists.
465
466If keyword arguments are present, they are first converted to
467positional arguments, as follows. First, a list of unfilled slots is
468created for the formal parameters. If there are N positional
469arguments, they are placed in the first N slots. Next, for each
470keyword argument, the identifier is used to determine the
471corresponding slot (if the identifier is the same as the first formal
472parameter name, the first slot is used, and so on). If the slot is
473already filled, a \exception{TypeError} exception is raised.
474Otherwise, the value of the argument is placed in the slot, filling it
475(even if the expression is \code{None}, it fills the slot). When all
476arguments have been processed, the slots that are still unfilled are
477filled with the corresponding default value from the function
478definition. (Default values are calculated, once, when the function
479is defined; thus, a mutable object such as a list or dictionary used
480as default value will be shared by all calls that don't specify an
481argument value for the corresponding slot; this should usually be
482avoided.) If there are any unfilled slots for which no default value
483is specified, a \exception{TypeError} exception is raised. Otherwise,
484the list of filled slots is used as the argument list for the call.
485
486If there are more positional arguments than there are formal parameter
487slots, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000488parameter using the syntax \samp{*identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000489case, that formal parameter receives a tuple containing the excess
490positional arguments (or an empty tuple if there were no excess
491positional arguments).
492
493If any keyword argument does not correspond to a formal parameter
494name, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000495parameter using the syntax \samp{**identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000496case, that formal parameter receives a dictionary containing the
497excess keyword arguments (using the keywords as keys and the argument
498values as corresponding values), or a (new) empty dictionary if there
499were no excess keyword arguments.
500
Michael W. Hudson850d3982001-12-12 11:56:33 +0000501If the syntax \samp{*expression} appears in the function call,
502\samp{expression} must evaluate to a sequence. Elements from this
503sequence are treated as if they were additional positional arguments;
504if there are postional arguments \var{x1},...,\var{xN} , and
505\samp{expression} evaluates to a sequence \var{y1},...,\var{yM}, this
506is equivalent to a call with M+N positional arguments
507\var{x1},...,\var{xN},\var{y1},...,\var{yM}.
508
509A consequence of this is that although the \samp{*expression} syntax
510appears \emph{after} any keyword arguments, it is processed
Fred Drakeb062cb22001-12-14 16:57:31 +0000511\emph{before} the keyword arguments (and the
512\samp{**expression} argument, if any -- see below). So:
Michael W. Hudson850d3982001-12-12 11:56:33 +0000513
514\begin{verbatim}
515>>> def f(a, b):
516... print a, b
517...
518>>> f(b=1, *(2,))
5192 1
520>>> f(a=1, *(2,))
521Traceback (most recent call last):
522 File "<stdin>", line 1, in ?
523TypeError: f() got multiple values for keyword argument 'a'
524>>> f(1, *(2,))
5251 2
526\end{verbatim}
527
Fred Drakeb062cb22001-12-14 16:57:31 +0000528It is unusual for both keyword arguments and the
529\samp{*expression} syntax to be used in the same call, so in practice
530this confusion does not arise.
Michael W. Hudson850d3982001-12-12 11:56:33 +0000531
532If the syntax \samp{**expression} appears in the function call,
533\samp{expression} must evaluate to a (subclass of) dictionary, the
534contents of which are treated as additional keyword arguments. In the
535case of a keyword appearing in both \samp{expression} and as an
536explicit keyword argument, a \exception{TypeError} exception is
537raised.
538
Fred Drakeea81edf1998-11-25 17:51:15 +0000539Formal parameters using the syntax \samp{*identifier} or
540\samp{**identifier} cannot be used as positional argument slots or
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000541as keyword argument names. Formal parameters using the syntax
Fred Drakeea81edf1998-11-25 17:51:15 +0000542\samp{(sublist)} cannot be used as keyword argument names; the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000543outermost sublist corresponds to a single unnamed argument slot, and
544the argument value is assigned to the sublist using the usual tuple
545assignment rules after all other parameter processing is done.
Fred Drakef6669171998-05-06 19:52:49 +0000546
Fred Drake5c07d9b1998-05-14 19:37:06 +0000547A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000548raises an exception. How this value is computed depends on the type
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000549of the callable object.
550
551If it is---
Fred Drakef6669171998-05-06 19:52:49 +0000552
553\begin{description}
554
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000555\item[a user-defined function:] The code block for the function is
Fred Drakef6669171998-05-06 19:52:49 +0000556executed, passing it the argument list. The first thing the code
557block will do is bind the formal parameters to the arguments; this is
558described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000559\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000560function call.
561\indexii{function}{call}
562\indexiii{user-defined}{function}{call}
563\obindex{user-defined function}
564\obindex{function}
565
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000566\item[a built-in function or method:] The result is up to the
Fred Drake3d83fc32000-07-31 20:08:23 +0000567interpreter; see the \citetitle[../lib/built-in-funcs.html]{Python
568Library Reference} for the descriptions of built-in functions and
569methods.
Fred Drakef6669171998-05-06 19:52:49 +0000570\indexii{function}{call}
571\indexii{built-in function}{call}
572\indexii{method}{call}
573\indexii{built-in method}{call}
574\obindex{built-in method}
575\obindex{built-in function}
576\obindex{method}
577\obindex{function}
578
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000579\item[a class object:] A new instance of that class is returned.
Fred Drakef6669171998-05-06 19:52:49 +0000580\obindex{class}
581\indexii{class object}{call}
582
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000583\item[a class instance method:] The corresponding user-defined
Fred Drakef6669171998-05-06 19:52:49 +0000584function is called, with an argument list that is one longer than the
585argument list of the call: the instance becomes the first argument.
586\obindex{class instance}
587\obindex{instance}
Fred Drakef6669171998-05-06 19:52:49 +0000588\indexii{class instance}{call}
589
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000590\item[a class instance:] The class must define a \method{__call__()}
591method; the effect is then the same as if that method was called.
592\indexii{instance}{call}
Fred Drakeea81edf1998-11-25 17:51:15 +0000593\withsubitem{(object method)}{\ttindex{__call__()}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000594
Fred Drakef6669171998-05-06 19:52:49 +0000595\end{description}
596
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000597
Fred Drake020f8c01998-07-28 19:32:59 +0000598\section{The power operator\label{power}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000599
600The power operator binds more tightly than unary operators on its
601left; it binds less tightly than unary operators on its right. The
602syntax is:
603
Fred Drakecb4638a2001-07-06 22:49:53 +0000604\begin{productionlist}
605 \production{power}
606 {\token{primary} ["**" \token{u_expr}]}
607\end{productionlist}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000608
609Thus, in an unparenthesized sequence of power and unary operators, the
610operators are evaluated from right to left (this does not constrain
611the evaluation order for the operands).
612
613The power operator has the same semantics as the built-in
614\function{pow()} function, when called with two arguments: it yields
615its left argument raised to the power of its right argument. The
616numeric arguments are first converted to a common type. The result
617type is that of the arguments after coercion; if the result is not
618expressible in that type (as in raising an integer to a negative
619power, or a negative floating point number to a broken power), a
620\exception{TypeError} exception is raised.
621
622
Fred Drakee15956b2000-04-03 04:51:13 +0000623\section{Unary arithmetic operations \label{unary}}
Fred Drakef6669171998-05-06 19:52:49 +0000624\indexiii{unary}{arithmetic}{operation}
625\indexiii{unary}{bit-wise}{operation}
626
627All unary arithmetic (and bit-wise) operations have the same priority:
628
Fred Drakecb4638a2001-07-06 22:49:53 +0000629\begin{productionlist}
630 \production{u_expr}
631 {\token{power} | "-" \token{u_expr}
Fred Drakef6eafc32002-03-18 16:47:14 +0000632 | "+" \token{u_expr} | "{\~}" \token{u_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000633\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000634
Fred Drake5c07d9b1998-05-14 19:37:06 +0000635The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000636numeric argument.
637\index{negation}
638\index{minus}
639
Fred Drake5c07d9b1998-05-14 19:37:06 +0000640The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000641unchanged.
642\index{plus}
643
Fred Drakee15956b2000-04-03 04:51:13 +0000644The unary \code{\~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000645of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000646\code{x} is defined as \code{-(x+1)}. It only applies to integral
647numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000648\index{inversion}
649
650In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000651a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000652\exindex{TypeError}
653
Fred Drake2829f1c2001-06-23 05:27:20 +0000654
Fred Drake020f8c01998-07-28 19:32:59 +0000655\section{Binary arithmetic operations\label{binary}}
Fred Drakef6669171998-05-06 19:52:49 +0000656\indexiii{binary}{arithmetic}{operation}
657
658The binary arithmetic operations have the conventional priority
659levels. Note that some of these operations also apply to certain
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000660non-numeric types. Apart from the power operator, there are only two
661levels, one for multiplicative operators and one for additive
Fred Drakef6669171998-05-06 19:52:49 +0000662operators:
663
Fred Drakecb4638a2001-07-06 22:49:53 +0000664\begin{productionlist}
665 \production{m_expr}
666 {\token{u_expr} | \token{m_expr} "*" \token{u_expr}
Fred Drake53815882002-03-15 23:21:37 +0000667 | \token{m_expr} "/" \token{u_expr}}
668 \productioncont{| \token{m_expr} "\%" \token{u_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000669 \production{a_expr}
670 {\token{m_expr} | \token{aexpr} "+" \token{m_expr}
671 \token{aexpr} "-" \token{m_expr}}
672\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000673
Fred Drake5c07d9b1998-05-14 19:37:06 +0000674The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000675arguments. The arguments must either both be numbers, or one argument
Fred Drakec3b18d72000-12-07 04:54:02 +0000676must be an integer (plain or long) and the other must be a sequence.
677In the former case, the numbers are converted to a common type and
678then multiplied together. In the latter case, sequence repetition is
Fred Drakef6669171998-05-06 19:52:49 +0000679performed; a negative repetition factor yields an empty sequence.
680\index{multiplication}
681
Fred Drake5c07d9b1998-05-14 19:37:06 +0000682The \code{/} (division) operator yields the quotient of its
Fred Drakef6669171998-05-06 19:52:49 +0000683arguments. The numeric arguments are first converted to a common
684type. Plain or long integer division yields an integer of the same
685type; the result is that of mathematical division with the `floor'
686function applied to the result. Division by zero raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000687\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000688\exindex{ZeroDivisionError}
689\index{division}
690
Fred Drake5c07d9b1998-05-14 19:37:06 +0000691The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000692division of the first argument by the second. The numeric arguments
693are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000694the \exception{ZeroDivisionError} exception. The arguments may be floating
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000695point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000696\code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
697yields a result with the same sign as its second operand (or zero);
698the absolute value of the result is strictly smaller than the second
699operand.
Fred Drakef6669171998-05-06 19:52:49 +0000700\index{modulo}
701
702The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000703following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
704modulo are also connected with the built-in function \function{divmod()}:
705\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Fred Drake1ea7c751999-05-06 14:46:35 +0000706floating point and complex numbers; there similar identities hold
707approximately where \code{x/y} is replaced by \code{floor(x/y)}) or
708\code{floor(x/y) - 1} (for floats),\footnote{
709 If x is very close to an exact integer multiple of y, it's
710 possible for \code{floor(x/y)} to be one larger than
711 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
712 the latter result, in order to preserve that \code{divmod(x,y)[0]
713 * y + x \%{} y} be very close to \code{x}.
714} or \code{floor((x/y).real)} (for
715complex).
Fred Drakef6669171998-05-06 19:52:49 +0000716
Fred Drake5c07d9b1998-05-14 19:37:06 +0000717The \code{+} (addition) operator yields the sum of its arguments.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000718The arguments must either both be numbers or both sequences of the
Fred Drakef6669171998-05-06 19:52:49 +0000719same type. In the former case, the numbers are converted to a common
720type and then added together. In the latter case, the sequences are
721concatenated.
722\index{addition}
723
Fred Drake5c07d9b1998-05-14 19:37:06 +0000724The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000725arguments. The numeric arguments are first converted to a common
726type.
727\index{subtraction}
728
Fred Drake2829f1c2001-06-23 05:27:20 +0000729
Fred Drake020f8c01998-07-28 19:32:59 +0000730\section{Shifting operations\label{shifting}}
Fred Drakef6669171998-05-06 19:52:49 +0000731\indexii{shifting}{operation}
732
733The shifting operations have lower priority than the arithmetic
734operations:
735
Fred Drakecb4638a2001-07-06 22:49:53 +0000736\begin{productionlist}
737 \production{shift_expr}
738 {\token{a_expr}
739 | \token{shift_expr} ( "<<" | ">>" ) \token{a_expr}}
740\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000741
742These operators accept plain or long integers as arguments. The
743arguments are converted to a common type. They shift the first
744argument to the left or right by the number of bits given by the
745second argument.
746
747A right shift by \var{n} bits is defined as division by
748\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
749multiplication with \code{pow(2,\var{n})}; for plain integers there is
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000750no overflow check so in that case the operation drops bits and flips
751the sign if the result is not less than \code{pow(2,31)} in absolute
752value. Negative shift counts raise a \exception{ValueError}
753exception.
Fred Drakef6669171998-05-06 19:52:49 +0000754\exindex{ValueError}
755
Fred Drake2829f1c2001-06-23 05:27:20 +0000756
Fred Drake020f8c01998-07-28 19:32:59 +0000757\section{Binary bit-wise operations\label{bitwise}}
Fred Drakef6669171998-05-06 19:52:49 +0000758\indexiii{binary}{bit-wise}{operation}
759
760Each of the three bitwise operations has a different priority level:
761
Fred Drakecb4638a2001-07-06 22:49:53 +0000762\begin{productionlist}
763 \production{and_expr}
764 {\token{shift_expr} | \token{and_expr} "\&" \token{shift_expr}}
765 \production{xor_expr}
766 {\token{and_expr} | \token{xor_expr} "\textasciicircum" \token{and_expr}}
767 \production{or_expr}
768 {\token{xor_expr} | \token{or_expr} "|" \token{xor_expr}}
769\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000770
Fred Drake5c07d9b1998-05-14 19:37:06 +0000771The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000772must be plain or long integers. The arguments are converted to a
773common type.
774\indexii{bit-wise}{and}
775
Fred Drake5c07d9b1998-05-14 19:37:06 +0000776The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000777arguments, which must be plain or long integers. The arguments are
778converted to a common type.
779\indexii{bit-wise}{xor}
780\indexii{exclusive}{or}
781
Fred Drake5c07d9b1998-05-14 19:37:06 +0000782The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000783arguments, which must be plain or long integers. The arguments are
784converted to a common type.
785\indexii{bit-wise}{or}
786\indexii{inclusive}{or}
787
Fred Drake2829f1c2001-06-23 05:27:20 +0000788
Fred Drake020f8c01998-07-28 19:32:59 +0000789\section{Comparisons\label{comparisons}}
Fred Drakef6669171998-05-06 19:52:49 +0000790\index{comparison}
791
Fred Drake1156f622000-09-19 18:10:05 +0000792Unlike C, all comparison operations in Python have the same priority,
793which is lower than that of any arithmetic, shifting or bitwise
794operation. Also unlike C, expressions like \code{a < b < c} have the
795interpretation that is conventional in mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000796\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000797
Fred Drakecb4638a2001-07-06 22:49:53 +0000798\begin{productionlist}
799 \production{comparison}
800 {\token{or_expr} ( \token{comp_operator} \token{or_expr} )*}
801 \production{comp_operator}
Fred Drake53815882002-03-15 23:21:37 +0000802 {"<" | ">" | "==" | ">=" | "<=" | "<>" | "!="}
803 \productioncont{| "is" ["not"] | ["not"] "in"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000804\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000805
Fred Drake5c07d9b1998-05-14 19:37:06 +0000806Comparisons yield integer values: \code{1} for true, \code{0} for false.
Fred Drakef6669171998-05-06 19:52:49 +0000807
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000808Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
Fred Drakef6669171998-05-06 19:52:49 +0000809equivalent to \code{x < y and y <= z}, except that \code{y} is
810evaluated only once (but in both cases \code{z} is not evaluated at all
811when \code{x < y} is found to be false).
812\indexii{chaining}{comparisons}
813
814Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
815expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
816operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000817to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
Fred Drakef6669171998-05-06 19:52:49 +0000818\var{y opy z}, except that each expression is evaluated at most once.
819
820Note that \var{a opa b opb c} doesn't imply any kind of comparison
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000821between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
Fred Drakef6669171998-05-06 19:52:49 +0000822perfectly legal (though perhaps not pretty).
823
Fred Drake5c07d9b1998-05-14 19:37:06 +0000824The forms \code{<>} and \code{!=} are equivalent; for consistency with
825C, \code{!=} is preferred; where \code{!=} is mentioned below
Fred Drake1156f622000-09-19 18:10:05 +0000826\code{<>} is also accepted. The \code{<>} spelling is considered
827obsolescent.
Fred Drakef6669171998-05-06 19:52:49 +0000828
Fred Drake1156f622000-09-19 18:10:05 +0000829The operators \code{<}, \code{>}, \code{==}, \code{>=}, \code{<=}, and
830\code{!=} compare
831the values of two objects. The objects need not have the same type.
Fred Drakef6669171998-05-06 19:52:49 +0000832If both are numbers, they are coverted to a common type. Otherwise,
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000833objects of different types \emph{always} compare unequal, and are
Fred Drakef6669171998-05-06 19:52:49 +0000834ordered consistently but arbitrarily.
835
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000836(This unusual definition of comparison was used to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000837definition of operations like sorting and the \keyword{in} and
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000838\keyword{not in} operators. In the future, the comparison rules for
839objects of different types are likely to change.)
Fred Drakef6669171998-05-06 19:52:49 +0000840
841Comparison of objects of the same type depends on the type:
842
843\begin{itemize}
844
845\item
846Numbers are compared arithmetically.
847
848\item
849Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +0000850(the result of the built-in function \function{ord()}) of their
Fred Drake1156f622000-09-19 18:10:05 +0000851characters. Unicode and 8-bit strings are fully interoperable in this
852behavior.
Fred Drakef6669171998-05-06 19:52:49 +0000853
854\item
855Tuples and lists are compared lexicographically using comparison of
856corresponding items.
857
858\item
Tim Peters20524db2001-10-01 20:22:45 +0000859Mappings (dictionaries) compare equal if and only if their sorted
860(key, value) lists compare equal.\footnote{The implementation computes
861 this efficiently, without constructing lists or sorting.}
862Outcomes other than equality are resolved consistently, but are not
Tim Peters1350c072001-10-01 20:25:26 +0000863otherwise defined.\footnote{Earlier versions of Python used
Tim Peters20524db2001-10-01 20:22:45 +0000864 lexicographic comparison of the sorted (key, value) lists, but this
865 was very expensive for the common case of comparing for equality. An
866 even earlier version of Python compared dictionaries by identity only,
867 but this caused surprises because people expected to be able to test
868 a dictionary for emptiness by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +0000869
870\item
871Most other types compare unequal unless they are the same object;
872the choice whether one object is considered smaller or larger than
873another one is made arbitrarily but consistently within one
874execution of a program.
875
876\end{itemize}
877
Fred Drake7399b9e2000-07-11 19:43:47 +0000878The operators \keyword{in} and \keyword{not in} test for set
Fred Drakeac79e952001-03-06 07:32:11 +0000879membership. \code{\var{x} in \var{s}} evaluates to true if \var{x}
880is a member of the set \var{s}, and false otherwise. \code{\var{x}
881not in \var{s}} returns the negation of \code{\var{x} in \var{s}}.
882The set membership test has traditionally been bound to sequences; an
883object is a member of a set if the set is a sequence and contains an
884element equal to that object. However, it is possible for an object
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +0000885to support membership tests without being a sequence. In particular,
886dictionaries support memership testing as a nicer way of spelling
887\code{\var{key} in \var{dict}}; other mapping types may follow suit.
Fred Drake7399b9e2000-07-11 19:43:47 +0000888
Fred Drake34bafcc2001-01-14 02:57:14 +0000889For the list and tuple types, \code{\var{x} in \var{y}} is true if and
Fred Drakeac79e952001-03-06 07:32:11 +0000890only if there exists an index \var{i} such that
Fred Drake34bafcc2001-01-14 02:57:14 +0000891\code{\var{x} == \var{y}[\var{i}]} is true.
Fred Drake7399b9e2000-07-11 19:43:47 +0000892
Fred Drake1156f622000-09-19 18:10:05 +0000893For the Unicode and string types, \code{\var{x} in \var{y}} is true if
894and only if there exists an index \var{i} such that \code{\var{x} ==
895\var{y}[\var{i}]} is true. If \code{\var{x}} is not a string or
896Unicode object of length \code{1}, a \exception{TypeError} exception
897is raised.
Fred Drake7399b9e2000-07-11 19:43:47 +0000898
899For user-defined classes which define the \method{__contains__()} method,
900\code{\var{x} in \var{y}} is true if and only if
901\code{\var{y}.__contains__(\var{x})} is true.
902
903For user-defined classes which do not define \method{__contains__()} and
Fred Drake1156f622000-09-19 18:10:05 +0000904do define \method{__getitem__()}, \code{\var{x} in \var{y}} is true if
905and only if there is a non-negative integer index \var{i} such that
Fred Drake7399b9e2000-07-11 19:43:47 +0000906\code{\var{x} == \var{y}[\var{i}]}, and all lower integer indices
907do not raise \exception{IndexError} exception. (If any other exception
908is raised, it is as if \keyword{in} raised that exception).
909
910The operator \keyword{not in} is defined to have the inverse true value
911of \keyword{in}.
Fred Drakef6669171998-05-06 19:52:49 +0000912\opindex{in}
913\opindex{not in}
914\indexii{membership}{test}
915\obindex{sequence}
916
Fred Drake5c07d9b1998-05-14 19:37:06 +0000917The operators \keyword{is} and \keyword{is not} test for object identity:
918\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
919are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +0000920truth value.
921\opindex{is}
922\opindex{is not}
923\indexii{identity}{test}
924
Fred Drake2829f1c2001-06-23 05:27:20 +0000925
Fred Drake020f8c01998-07-28 19:32:59 +0000926\section{Boolean operations\label{Booleans}}
Fred Drakef6669171998-05-06 19:52:49 +0000927\indexii{Boolean}{operation}
928
929Boolean operations have the lowest priority of all Python operations:
930
Fred Drakecb4638a2001-07-06 22:49:53 +0000931\begin{productionlist}
932 \production{expression}
933 {\token{or_test} | \token{lambda_form}}
934 \production{or_test}
935 {\token{and_test} | \token{or_test} "or" \token{and_test}}
936 \production{and_test}
937 {\token{not_test} | \token{and_test} "and" \token{not_test}}
938 \production{not_test}
939 {\token{comparison} | "not" \token{not_test}}
940 \production{lambda_form}
941 {"lambda" [\token{parameter_list}]: \token{expression}}
942\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000943
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000944In the context of Boolean operations, and also when expressions are
Fred Drakef6669171998-05-06 19:52:49 +0000945used by control flow statements, the following values are interpreted
Fred Drake5c07d9b1998-05-14 19:37:06 +0000946as false: \code{None}, numeric zero of all types, empty sequences
Fred Drakef6669171998-05-06 19:52:49 +0000947(strings, tuples and lists), and empty mappings (dictionaries). All
948other values are interpreted as true.
949
Fred Drake5c07d9b1998-05-14 19:37:06 +0000950The operator \keyword{not} yields \code{1} if its argument is false,
951\code{0} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +0000952\opindex{not}
953
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000954The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000955\var{x} is false, its value is returned; otherwise, \var{y} is
956evaluated and the resulting value is returned.
957\opindex{and}
958
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000959The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000960\var{x} is true, its value is returned; otherwise, \var{y} is
961evaluated and the resulting value is returned.
962\opindex{or}
963
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000964(Note that neither \keyword{and} nor \keyword{or} restrict the value
Fred Drake5c07d9b1998-05-14 19:37:06 +0000965and type they return to \code{0} and \code{1}, but rather return the
966last evaluated argument.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000967This is sometimes useful, e.g., if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +0000968replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +0000969\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +0000970invent a value anyway, it does not bother to return a value of the
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000971same type as its argument, so e.g., \code{not 'foo'} yields \code{0},
Fred Drake5c07d9b1998-05-14 19:37:06 +0000972not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +0000973
974Lambda forms (lambda expressions) have the same syntactic position as
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000975expressions. They are a shorthand to create anonymous functions; the
976expression \code{lambda \var{arguments}: \var{expression}}
Fred Drakef6669171998-05-06 19:52:49 +0000977yields a function object that behaves virtually identical to one
978defined with
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000979
980\begin{verbatim}
981def name(arguments):
982 return expression
983\end{verbatim}
984
985See section \ref{function} for the syntax of parameter lists. Note
986that functions created with lambda forms cannot contain statements.
Fred Drakef6669171998-05-06 19:52:49 +0000987\label{lambda}
988\indexii{lambda}{expression}
989\indexii{lambda}{form}
990\indexii{anonmymous}{function}
991
Fred Drake88382692001-06-05 02:17:02 +0000992\strong{Programmer's note:} Prior to Python 2.1, a lambda form defined
993inside a function has no access to names defined in the function's
994namespace. This is because Python had only two scopes: local and
995global. A common work-around was to use default argument values to
996pass selected variables into the lambda's namespace, e.g.:
Fred Drakef6669171998-05-06 19:52:49 +0000997
998\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000999def make_incrementor(increment):
1000 return lambda x, n=increment: x+n
Fred Drakef6669171998-05-06 19:52:49 +00001001\end{verbatim}
1002
Fred Drake88382692001-06-05 02:17:02 +00001003As of Python 2.1, nested scopes were introduced, and this work-around
1004has not been necessary. Python 2.1 supports nested scopes in modules
1005which include the statement \samp{from __future__ import
1006nested_scopes}, and more recent versions of Python enable nested
1007scopes by default. This version works starting with Python 2.1:
1008
1009\begin{verbatim}
1010from __future__ import nested_scopes
1011
1012def make_incrementor(increment):
1013 return lambda x: x+increment
1014\end{verbatim}
1015
1016
Fred Drake020f8c01998-07-28 19:32:59 +00001017\section{Expression lists\label{exprlists}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001018\indexii{expression}{list}
Fred Drakef6669171998-05-06 19:52:49 +00001019
Fred Drakecb4638a2001-07-06 22:49:53 +00001020\begin{productionlist}
1021 \production{expression_list}
1022 {\token{expression} ( "," \token{expression} )* [","]}
1023\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +00001024
Fred Drakec009d192000-04-25 21:09:10 +00001025An expression list containing at least one comma yields a
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001026tuple. The length of the tuple is the number of expressions in the
1027list. The expressions are evaluated from left to right.
Fred Drakef6669171998-05-06 19:52:49 +00001028\obindex{tuple}
1029
1030The trailing comma is required only to create a single tuple (a.k.a. a
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001031\emph{singleton}); it is optional in all other cases. A single
Fred Drakec009d192000-04-25 21:09:10 +00001032expression without a trailing comma doesn't create a
1033tuple, but rather yields the value of that expression.
Fred Drakef6669171998-05-06 19:52:49 +00001034(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +00001035\code{()}.)
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001036\indexii{trailing}{comma}
Fred Drakef6669171998-05-06 19:52:49 +00001037
Fred Draked09120b1999-04-29 16:43:42 +00001038
Fred Drake020f8c01998-07-28 19:32:59 +00001039\section{Summary\label{summary}}
Fred Drakef6669171998-05-06 19:52:49 +00001040
Fred Draked09120b1999-04-29 16:43:42 +00001041The following table summarizes the operator
1042precedences\indexii{operator}{precedence} in Python, from lowest
1043precedence (least binding) to highest precedence (most binding).
1044Operators in the same box have the same precedence. Unless the syntax
1045is explicitly given, operators are binary. Operators in the same box
1046group left to right (except for comparisons, which chain from left to
Fred Drake2a222002000-12-11 22:39:24 +00001047right --- see above, and exponentiation, which groups from right to
1048left).
Fred Drakef6669171998-05-06 19:52:49 +00001049
Fred Draked09120b1999-04-29 16:43:42 +00001050\begin{tableii}{c|l}{textrm}{Operator}{Description}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001051 \lineii{\keyword{lambda}} {Lambda expression}
1052 \hline
1053 \lineii{\keyword{or}} {Boolean OR}
1054 \hline
1055 \lineii{\keyword{and}} {Boolean AND}
1056 \hline
1057 \lineii{\keyword{not} \var{x}} {Boolean NOT}
1058 \hline
1059 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
1060 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
1061 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
Fred Drake9beee801998-10-21 00:44:49 +00001062 \code{<>}, \code{!=}, \code{==}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001063 {Comparisons}
1064 \hline
1065 \lineii{\code{|}} {Bitwise OR}
1066 \hline
1067 \lineii{\code{\^}} {Bitwise XOR}
1068 \hline
1069 \lineii{\code{\&}} {Bitwise AND}
1070 \hline
Fred Drake24e7a292001-04-12 12:37:03 +00001071 \lineii{\code{<}\code{<}, \code{>}\code{>}} {Shifts}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001072 \hline
1073 \lineii{\code{+}, \code{-}}{Addition and subtraction}
1074 \hline
Fred Drake9beee801998-10-21 00:44:49 +00001075 \lineii{\code{*}, \code{/}, \code{\%}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001076 {Multiplication, division, remainder}
1077 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001078 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
1079 \lineii{\code{\~\var{x}}} {Bitwise not}
1080 \hline
Fred Drakeb8ac0092001-05-09 16:51:49 +00001081 \lineii{\code{**}} {Exponentiation}
1082 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001083 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
1084 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
1085 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
1086 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
Fred Draked09120b1999-04-29 16:43:42 +00001087 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001088 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
1089 \lineii{\code{[\var{expressions}\ldots]}} {List display}
1090 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
1091 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
1092\end{tableii}