blob: 95e66de1813d9c2d73383f153b2930525db62adc [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}}
Guido van Rossumd8faa362007-04-27 19:54:29 +000059 \productioncont{| \token{string_conversion} | \token{yield_atom}}
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
Guido van Rossumd8faa362007-04-27 19:54:29 +000068section \ref{identifiers} for lexical definition and
Fred Drakec0678ff2003-09-06 03:33:32 +000069section~\ref{naming} for documentation of naming and binding.
Fred Drakef6669171998-05-06 19:52:49 +000070
71When the name is bound to an object, evaluation of the atom yields
72that object. When a name is not bound, an attempt to evaluate it
Fred Drake5c07d9b1998-05-14 19:37:06 +000073raises a \exception{NameError} exception.
Fred Drakef6669171998-05-06 19:52:49 +000074\exindex{NameError}
75
Fred Drakec0678ff2003-09-06 03:33:32 +000076\strong{Private name mangling:}
Guido van Rossum3a0ad601998-07-23 21:57:42 +000077\indexii{name}{mangling}%
78\indexii{private}{names}%
Fred Drakec0678ff2003-09-06 03:33:32 +000079When an identifier that textually occurs in a class definition begins
Guido van Rossum3a0ad601998-07-23 21:57:42 +000080with two or more underscore characters and does not end in two or more
Fred Drakeea81edf1998-11-25 17:51:15 +000081underscores, it is considered a \dfn{private name} of that class.
Guido van Rossum3a0ad601998-07-23 21:57:42 +000082Private names are transformed to a longer form before code is
83generated for them. The transformation inserts the class name in
84front of the name, with leading underscores removed, and a single
85underscore inserted in front of the class name. For example, the
86identifier \code{__spam} occurring in a class named \code{Ham} will be
87transformed to \code{_Ham__spam}. This transformation is independent
88of the syntactical context in which the identifier is used. If the
89transformed name is extremely long (longer than 255 characters),
90implementation defined truncation may happen. If the class name
91consists only of underscores, no transformation is done.
92
Fred Drake2829f1c2001-06-23 05:27:20 +000093
Fred Drake020f8c01998-07-28 19:32:59 +000094\subsection{Literals\label{atom-literals}}
Fred Drakef6669171998-05-06 19:52:49 +000095\index{literal}
96
Guido van Rossum3a0ad601998-07-23 21:57:42 +000097Python supports string literals and various numeric literals:
Fred Drakef6669171998-05-06 19:52:49 +000098
Fred Drakecb4638a2001-07-06 22:49:53 +000099\begin{productionlist}
100 \production{literal}
Fred Drake53815882002-03-15 23:21:37 +0000101 {\token{stringliteral} | \token{integer} | \token{longinteger}}
102 \productioncont{| \token{floatnumber} | \token{imagnumber}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000103\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000104
105Evaluation of a literal yields an object of the given type (string,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000106integer, long integer, floating point number, complex number) with the
107given value. The value may be approximated in the case of floating
108point and imaginary (complex) literals. See section \ref{literals}
109for details.
Fred Drakef6669171998-05-06 19:52:49 +0000110
111All literals correspond to immutable data types, and hence the
112object's identity is less important than its value. Multiple
113evaluations of literals with the same value (either the same
114occurrence in the program text or a different occurrence) may obtain
115the same object or a different object with the same value.
116\indexiii{immutable}{data}{type}
Fred Drakee15956b2000-04-03 04:51:13 +0000117\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000118
Fred Drake2829f1c2001-06-23 05:27:20 +0000119
Fred Drake020f8c01998-07-28 19:32:59 +0000120\subsection{Parenthesized forms\label{parenthesized}}
Fred Drakef6669171998-05-06 19:52:49 +0000121\index{parenthesized form}
122
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000123A parenthesized form is an optional expression list enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000124parentheses:
125
Fred Drakecb4638a2001-07-06 22:49:53 +0000126\begin{productionlist}
127 \production{parenth_form}
128 {"(" [\token{expression_list}] ")"}
129\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000130
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000131A parenthesized expression list yields whatever that expression list
132yields: if the list contains at least one comma, it yields a tuple;
133otherwise, it yields the single expression that makes up the
134expression list.
Fred Drakef6669171998-05-06 19:52:49 +0000135
136An empty pair of parentheses yields an empty tuple object. Since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000137tuples are immutable, the rules for literals apply (i.e., two
138occurrences of the empty tuple may or may not yield the same object).
Fred Drakef6669171998-05-06 19:52:49 +0000139\indexii{empty}{tuple}
140
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000141Note that tuples are not formed by the parentheses, but rather by use
Fred Drakef6669171998-05-06 19:52:49 +0000142of the comma operator. The exception is the empty tuple, for which
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000143parentheses \emph{are} required --- allowing unparenthesized ``nothing''
Fred Drakef6669171998-05-06 19:52:49 +0000144in expressions would cause ambiguities and allow common typos to
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000145pass uncaught.
Fred Drakef6669171998-05-06 19:52:49 +0000146\index{comma}
147\indexii{tuple}{display}
148
Fred Drake2829f1c2001-06-23 05:27:20 +0000149
Fred Drake020f8c01998-07-28 19:32:59 +0000150\subsection{List displays\label{lists}}
Fred Drakef6669171998-05-06 19:52:49 +0000151\indexii{list}{display}
Skip Montanarob6559392000-09-11 16:31:55 +0000152\indexii{list}{comprehensions}
Fred Drakef6669171998-05-06 19:52:49 +0000153
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000154A list display is a possibly empty series of expressions enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000155square brackets:
156
Fred Drakecb4638a2001-07-06 22:49:53 +0000157\begin{productionlist}
158 \production{list_display}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000159 {"[" [\token{expression_list} | \token{list_comprehension}] "]"}
160 \production{list_comprehension}
161 {\token{expression} \token{list_for}}
162 \production{list_for}
163 {"for" \token{target_list} "in" \token{old_expression_list}
164 [\token{list_iter}]}
165 \production{old_expression_list}
166 {\token{old_expression}
167 [("," \token{old_expression})+ [","]]}
Fred Drakecb4638a2001-07-06 22:49:53 +0000168 \production{list_iter}
169 {\token{list_for} | \token{list_if}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000170 \production{list_if}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000171 {"if" \token{old_expression} [\token{list_iter}]}
Fred Drakecb4638a2001-07-06 22:49:53 +0000172\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000173
Skip Montanaro803d6e52000-08-12 18:09:51 +0000174A list display yields a new list object. Its contents are specified
175by providing either a list of expressions or a list comprehension.
Skip Montanarob6559392000-09-11 16:31:55 +0000176\indexii{list}{comprehensions}
Skip Montanaro803d6e52000-08-12 18:09:51 +0000177When a comma-separated list of expressions is supplied, its elements are
178evaluated from left to right and placed into the list object in that
179order. When a list comprehension is supplied, it consists of a
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000180single expression followed by at least one \keyword{for} clause and zero or
Tim Peters20524db2001-10-01 20:22:45 +0000181more \keyword{for} or \keyword{if} clauses. In this
Skip Montanaro803d6e52000-08-12 18:09:51 +0000182case, the elements of the new list are those that would be produced
Skip Montanaro323fe5d2000-08-23 17:03:34 +0000183by considering each of the \keyword{for} or \keyword{if} clauses a block,
Tim Peters20524db2001-10-01 20:22:45 +0000184nesting from
Skip Montanaro803d6e52000-08-12 18:09:51 +0000185left to right, and evaluating the expression to produce a list element
Andrew M. Kuchlingcbd81552004-08-07 19:16:32 +0000186each time the innermost block is reached\footnote{In Python 2.3, a
187list comprehension "leaks" the control variables of each
188\samp{for} it contains into the containing scope. However, this
189behavior is deprecated, and relying on it will not work once this
190bug is fixed in a future release}.
Fred Drakef6669171998-05-06 19:52:49 +0000191\obindex{list}
Fred Drakef6669171998-05-06 19:52:49 +0000192\indexii{empty}{list}
193
Fred Drake2829f1c2001-06-23 05:27:20 +0000194
Raymond Hettinger5c8d29c2004-08-15 23:28:10 +0000195\subsection{Generator expressions\label{genexpr}}
196\indexii{generator}{expression}
197
198A generator expression is a compact generator notation in parentheses:
199
200\begin{productionlist}
201 \production{generator_expression}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000202 {"(" \token{expression} \token{genexpr_for} ")"}
Raymond Hettinger5c8d29c2004-08-15 23:28:10 +0000203 \production{genexpr_for}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000204 {"for" \token{target_list} "in" \token{or_test}
Raymond Hettinger5c8d29c2004-08-15 23:28:10 +0000205 [\token{genexpr_iter}]}
206 \production{genexpr_iter}
207 {\token{genexpr_for} | \token{genexpr_if}}
208 \production{genexpr_if}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000209 {"if" \token{old_expression} [\token{genexpr_iter}]}
Raymond Hettinger5c8d29c2004-08-15 23:28:10 +0000210\end{productionlist}
211
212A generator expression yields a new generator object.
213\obindex{generator}
Raymond Hettinger5c8d29c2004-08-15 23:28:10 +0000214It consists of a single expression followed by at least one
215\keyword{for} clause and zero or more \keyword{for} or \keyword{if}
216clauses. The iterating values of the new generator are those that
217would be produced by considering each of the \keyword{for} or
218\keyword{if} clauses a block, nesting from left to right, and
219evaluating the expression to yield a value that is reached the
220innermost block for each iteration.
221
222Variables used in the generator expression are evaluated lazily
Georg Brandla18af4e2007-04-21 15:47:16 +0000223when the \method{__next__()} method is called for generator object
Raymond Hettinger5c8d29c2004-08-15 23:28:10 +0000224(in the same fashion as normal generators). However, the leftmost
225\keyword{for} clause is immediately evaluated so that error produced
226by it can be seen before any other possible error in the code that
227handles the generator expression.
228Subsequent \keyword{for} clauses cannot be evaluated immediately since
229they may depend on the previous \keyword{for} loop.
230For example: \samp{(x*y for x in range(10) for y in bar(x))}.
231
232The parentheses can be omitted on calls with only one argument.
233See section \ref{calls} for the detail.
234
235
Fred Drake020f8c01998-07-28 19:32:59 +0000236\subsection{Dictionary displays\label{dict}}
Fred Drakef6669171998-05-06 19:52:49 +0000237\indexii{dictionary}{display}
238
239A dictionary display is a possibly empty series of key/datum pairs
240enclosed in curly braces:
241\index{key}
242\index{datum}
243\index{key/datum pair}
244
Fred Drakecb4638a2001-07-06 22:49:53 +0000245\begin{productionlist}
246 \production{dict_display}
Fred Drake83d14c12002-03-16 06:35:54 +0000247 {"\{" [\token{key_datum_list}] "\}"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000248 \production{key_datum_list}
249 {\token{key_datum} ("," \token{key_datum})* [","]}
250 \production{key_datum}
251 {\token{expression} ":" \token{expression}}
252\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000253
254A dictionary display yields a new dictionary object.
255\obindex{dictionary}
256
257The key/datum pairs are evaluated from left to right to define the
258entries of the dictionary: each key object is used as a key into the
259dictionary to store the corresponding datum.
260
261Restrictions on the types of the key values are listed earlier in
Raymond Hettinger68804312005-01-01 00:28:46 +0000262section \ref{types}. (To summarize, the key type should be hashable,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000263which excludes all mutable objects.) Clashes between duplicate keys
264are not detected; the last datum (textually rightmost in the display)
265stored for a given key value prevails.
Fred Drakee15956b2000-04-03 04:51:13 +0000266\indexii{immutable}{object}
Fred Drakef6669171998-05-06 19:52:49 +0000267
Fred Drake2829f1c2001-06-23 05:27:20 +0000268
Guido van Rossumd8faa362007-04-27 19:54:29 +0000269\subsection{Yield expressions\label{yieldexpr}}
270\kwindex{yield}
271\indexii{yield}{expression}
272\indexii{generator}{function}
273
274\begin{productionlist}
275 \production{yield_atom}
276 {"(" \token{yield_expression} ")"}
277 \production{yield_expression}
278 {"yield" [\token{expression_list}]}
279\end{productionlist}
280
281\versionadded{2.5}
282
283The \keyword{yield} expression is only used when defining a generator
284function, and can only be used in the body of a function definition.
285Using a \keyword{yield} expression in a function definition is
286sufficient to cause that definition to create a generator function
287instead of a normal function.
288
289When a generator function is called, it returns an iterator known as a
290generator. That generator then controls the execution of a generator
291function. The execution starts when one of the generator's methods is
292called. At that time, the execution proceeds to the first
293\keyword{yield} expression, where it is suspended again, returning the
294value of \grammartoken{expression_list} to generator's caller. By
295suspended we mean that all local state is retained, including the
296current bindings of local variables, the instruction pointer, and the
297internal evaluation stack. When the execution is resumed by calling
298one of the generator's methods, the function can proceed exactly as
299if the \keyword{yield} expression was just another external call.
300The value of the \keyword{yield} expression after resuming depends on
301the method which resumed the execution.
302
303\index{coroutine}
304
305All of this makes generator functions quite similar to coroutines; they
306yield multiple times, they have more than one entry point and their
307execution can be suspended. The only difference is that a generator
308function cannot control where should the execution continue after it
309yields; the control is always transfered to the generator's caller.
310
311\obindex{generator}
312
313The following generator's methods can be used to control the execution
314of a generator function:
315
316\exindex{StopIteration}
317
318\begin{methoddesc}[generator]{next}{}
319 Starts the execution of a generator function or resumes it at the
320 last executed \keyword{yield} expression. When a generator function
321 is resumed with a \method{next()} method, the current \keyword{yield}
322 expression always evaluates to \constant{None}. The execution then
323 continues to the next \keyword{yield} expression, where the generator
324 is suspended again, and the value of the
325 \grammartoken{expression_list} is returned to \method{next()}'s
326 caller. If the generator exits without yielding another value, a
327 \exception{StopIteration} exception is raised.
328\end{methoddesc}
329
330\begin{methoddesc}[generator]{send}{value}
331 Resumes the execution and ``sends'' a value into the generator
332 function. The \code{value} argument becomes the result of the
333 current \keyword{yield} expression. The \method{send()} method
334 returns the next value yielded by the generator, or raises
335 \exception{StopIteration} if the generator exits without yielding
336 another value.
337 When \method{send()} is called to start the generator, it must be
338 called with \constant{None} as the argument, because there is no
339 \keyword{yield} expression that could receieve the value.
340\end{methoddesc}
341
342\begin{methoddesc}[generator]{throw}
343 {type\optional{, value\optional{, traceback}}}
344 Raises an exception of type \code{type} at the point where generator
345 was paused, and returns the next value yielded by the generator
346 function. If the generator exits without yielding another value, a
347 \exception{StopIteration} exception is raised. If the generator
348 function does not catch the passed-in exception, or raises a
349 different exception, then that exception propagates to the caller.
350\end{methoddesc}
351
352\exindex{GeneratorExit}
353
354\begin{methoddesc}[generator]{close}{}
355 Raises a \exception{GeneratorExit} at the point where the generator
356 function was paused. If the generator function then raises
357 \exception{StopIteration} (by exiting normally, or due to already
358 being closed) or \exception{GeneratorExit} (by not catching the
359 exception), close returns to its caller. If the generator yields a
360 value, a \exception{RuntimeError} is raised. If the generator raises
361 any other exception, it is propagated to the caller. \method{close}
362 does nothing if the generator has already exited due to an exception
363 or normal exit.
364\end{methoddesc}
365
366Here is a simple example that demonstrates the behavior of generators
367and generator functions:
368
369\begin{verbatim}
370>>> def echo(value=None):
371... print "Execution starts when 'next()' is called for the first time."
372... try:
373... while True:
374... try:
375... value = (yield value)
376... except GeneratorExit:
377... # never catch GeneratorExit
378... raise
379... except Exception, e:
380... value = e
381... finally:
382... print "Don't forget to clean up when 'close()' is called."
383...
384>>> generator = echo(1)
385>>> print generator.next()
386Execution starts when 'next()' is called for the first time.
3871
388>>> print generator.next()
389None
390>>> print generator.send(2)
3912
392>>> generator.throw(TypeError, "spam")
393TypeError('spam',)
394>>> generator.close()
395Don't forget to clean up when 'close()' is called.
396\end{verbatim}
397
398\begin{seealso}
399 \seepep{0342}{Coroutines via Enhanced Generators}
400 {The proposal to enhance the API and syntax of generators,
401 making them usable as simple coroutines.}
402\end{seealso}
403
404
Fred Drake020f8c01998-07-28 19:32:59 +0000405\section{Primaries\label{primaries}}
Fred Drakef6669171998-05-06 19:52:49 +0000406\index{primary}
407
408Primaries represent the most tightly bound operations of the language.
409Their syntax is:
410
Fred Drakecb4638a2001-07-06 22:49:53 +0000411\begin{productionlist}
412 \production{primary}
413 {\token{atom} | \token{attributeref}
414 | \token{subscription} | \token{slicing} | \token{call}}
415\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000416
Fred Drake2829f1c2001-06-23 05:27:20 +0000417
Fred Drake020f8c01998-07-28 19:32:59 +0000418\subsection{Attribute references\label{attribute-references}}
Fred Drakef6669171998-05-06 19:52:49 +0000419\indexii{attribute}{reference}
420
421An attribute reference is a primary followed by a period and a name:
422
Fred Drakecb4638a2001-07-06 22:49:53 +0000423\begin{productionlist}
424 \production{attributeref}
425 {\token{primary} "." \token{identifier}}
426\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000427
428The primary must evaluate to an object of a type that supports
Fred Drake34bafcc2001-01-14 02:57:14 +0000429attribute references, e.g., a module, list, or an instance. This
430object is then asked to produce the attribute whose name is the
431identifier. If this attribute is not available, the exception
Fred Drake5c07d9b1998-05-14 19:37:06 +0000432\exception{AttributeError}\exindex{AttributeError} is raised.
433Otherwise, the type and value of the object produced is determined by
434the object. Multiple evaluations of the same attribute reference may
435yield different objects.
Fred Drakef6669171998-05-06 19:52:49 +0000436\obindex{module}
437\obindex{list}
438
Fred Drake2829f1c2001-06-23 05:27:20 +0000439
Fred Drake020f8c01998-07-28 19:32:59 +0000440\subsection{Subscriptions\label{subscriptions}}
Fred Drakef6669171998-05-06 19:52:49 +0000441\index{subscription}
442
443A subscription selects an item of a sequence (string, tuple or list)
444or mapping (dictionary) object:
445\obindex{sequence}
446\obindex{mapping}
447\obindex{string}
448\obindex{tuple}
449\obindex{list}
450\obindex{dictionary}
451\indexii{sequence}{item}
452
Fred Drakecb4638a2001-07-06 22:49:53 +0000453\begin{productionlist}
454 \production{subscription}
455 {\token{primary} "[" \token{expression_list} "]"}
456\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000457
458The primary must evaluate to an object of a sequence or mapping type.
459
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000460If the primary is a mapping, the expression list must evaluate to an
461object whose value is one of the keys of the mapping, and the
462subscription selects the value in the mapping that corresponds to that
463key. (The expression list is a tuple except if it has exactly one
464item.)
Fred Drakef6669171998-05-06 19:52:49 +0000465
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000466If the primary is a sequence, the expression (list) must evaluate to a
467plain integer. If this value is negative, the length of the sequence
468is added to it (so that, e.g., \code{x[-1]} selects the last item of
469\code{x}.) The resulting value must be a nonnegative integer less
470than the number of items in the sequence, and the subscription selects
471the item whose index is that value (counting from zero).
Fred Drakef6669171998-05-06 19:52:49 +0000472
473A string's items are characters. A character is not a separate data
474type but a string of exactly one character.
475\index{character}
476\indexii{string}{item}
477
Fred Drake2829f1c2001-06-23 05:27:20 +0000478
Fred Drake020f8c01998-07-28 19:32:59 +0000479\subsection{Slicings\label{slicings}}
Fred Drakef6669171998-05-06 19:52:49 +0000480\index{slicing}
481\index{slice}
482
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000483A slicing selects a range of items in a sequence object (e.g., a
484string, tuple or list). Slicings may be used as expressions or as
Thomas Wouters477c8d52006-05-27 19:21:47 +0000485targets in assignment or \keyword{del} statements. The syntax for a
486slicing:
Fred Drakef6669171998-05-06 19:52:49 +0000487\obindex{sequence}
488\obindex{string}
489\obindex{tuple}
490\obindex{list}
491
Fred Drakecb4638a2001-07-06 22:49:53 +0000492\begin{productionlist}
493 \production{slicing}
494 {\token{simple_slicing} | \token{extended_slicing}}
495 \production{simple_slicing}
496 {\token{primary} "[" \token{short_slice} "]"}
497 \production{extended_slicing}
498 {\token{primary} "[" \token{slice_list} "]" }
499 \production{slice_list}
500 {\token{slice_item} ("," \token{slice_item})* [","]}
501 \production{slice_item}
502 {\token{expression} | \token{proper_slice} | \token{ellipsis}}
503 \production{proper_slice}
504 {\token{short_slice} | \token{long_slice}}
505 \production{short_slice}
506 {[\token{lower_bound}] ":" [\token{upper_bound}]}
507 \production{long_slice}
508 {\token{short_slice} ":" [\token{stride}]}
509 \production{lower_bound}
510 {\token{expression}}
511 \production{upper_bound}
512 {\token{expression}}
513 \production{stride}
514 {\token{expression}}
515 \production{ellipsis}
516 {"..."}
517\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000518
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000519There is ambiguity in the formal syntax here: anything that looks like
520an expression list also looks like a slice list, so any subscription
521can be interpreted as a slicing. Rather than further complicating the
522syntax, this is disambiguated by defining that in this case the
523interpretation as a subscription takes priority over the
524interpretation as a slicing (this is the case if the slice list
525contains no proper slice nor ellipses). Similarly, when the slice
526list has exactly one short slice and no trailing comma, the
527interpretation as a simple slicing takes priority over that as an
528extended slicing.\indexii{extended}{slicing}
529
530The semantics for a simple slicing are as follows. The primary must
531evaluate to a sequence object. The lower and upper bound expressions,
532if present, must evaluate to plain integers; defaults are zero and the
Fred Drakee15956b2000-04-03 04:51:13 +0000533\code{sys.maxint}, respectively. If either bound is negative, the
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000534sequence's length is added to it. The slicing now selects all items
535with index \var{k} such that
Fred Drakef6669171998-05-06 19:52:49 +0000536\code{\var{i} <= \var{k} < \var{j}} where \var{i}
537and \var{j} are the specified lower and upper bounds. This may be an
538empty sequence. It is not an error if \var{i} or \var{j} lie outside the
539range of valid indexes (such items don't exist so they aren't
540selected).
541
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000542The semantics for an extended slicing are as follows. The primary
543must evaluate to a mapping object, and it is indexed with a key that
544is constructed from the slice list, as follows. If the slice list
545contains at least one comma, the key is a tuple containing the
546conversion of the slice items; otherwise, the conversion of the lone
547slice item is the key. The conversion of a slice item that is an
Georg Brandl52318d62006-09-06 07:06:08 +0000548expression is that expression. The conversion of a
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000549proper slice is a slice object (see section \ref{types}) whose
Fred Drakeea81edf1998-11-25 17:51:15 +0000550\member{start}, \member{stop} and \member{step} attributes are the
551values of the expressions given as lower bound, upper bound and
552stride, respectively, substituting \code{None} for missing
553expressions.
Fred Drake99cd5731999-02-12 20:40:09 +0000554\withsubitem{(slice object attribute)}{\ttindex{start}
555 \ttindex{stop}\ttindex{step}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000556
Fred Drake2829f1c2001-06-23 05:27:20 +0000557
Fred Drake020f8c01998-07-28 19:32:59 +0000558\subsection{Calls\label{calls}}
Fred Drakef6669171998-05-06 19:52:49 +0000559\index{call}
560
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000561A call calls a callable object (e.g., a function) with a possibly empty
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000562series of arguments:
Fred Drakef6669171998-05-06 19:52:49 +0000563\obindex{callable}
564
Fred Drakecb4638a2001-07-06 22:49:53 +0000565\begin{productionlist}
566 \production{call}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000567 {\token{primary} "(" [\token{argument_list} [","]}
568 \productioncont{ | \token{expression} \token{genexpr_for}] ")"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000569 \production{argument_list}
Fred Drake74653822002-10-07 16:28:38 +0000570 {\token{positional_arguments} ["," \token{keyword_arguments}]}
571 \productioncont{ ["," "*" \token{expression}]}
572 \productioncont{ ["," "**" \token{expression}]}
573 \productioncont{| \token{keyword_arguments} ["," "*" \token{expression}]}
574 \productioncont{ ["," "**" \token{expression}]}
Fred Drake53815882002-03-15 23:21:37 +0000575 \productioncont{| "*" \token{expression} ["," "**" \token{expression}]}
576 \productioncont{| "**" \token{expression}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000577 \production{positional_arguments}
578 {\token{expression} ("," \token{expression})*}
579 \production{keyword_arguments}
580 {\token{keyword_item} ("," \token{keyword_item})*}
581 \production{keyword_item}
582 {\token{identifier} "=" \token{expression}}
583\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000584
Fred Drake9a408512004-11-02 18:57:33 +0000585A trailing comma may be present after the positional and keyword
586arguments but does not affect the semantics.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000587
Fred Drakef6669171998-05-06 19:52:49 +0000588The primary must evaluate to a callable object (user-defined
589functions, built-in functions, methods of built-in objects, class
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000590objects, methods of class instances, and certain class instances
591themselves are callable; extensions may define additional callable
592object types). All argument expressions are evaluated before the call
593is attempted. Please refer to section \ref{function} for the syntax
594of formal parameter lists.
595
596If keyword arguments are present, they are first converted to
597positional arguments, as follows. First, a list of unfilled slots is
598created for the formal parameters. If there are N positional
599arguments, they are placed in the first N slots. Next, for each
600keyword argument, the identifier is used to determine the
601corresponding slot (if the identifier is the same as the first formal
602parameter name, the first slot is used, and so on). If the slot is
603already filled, a \exception{TypeError} exception is raised.
604Otherwise, the value of the argument is placed in the slot, filling it
605(even if the expression is \code{None}, it fills the slot). When all
606arguments have been processed, the slots that are still unfilled are
607filled with the corresponding default value from the function
608definition. (Default values are calculated, once, when the function
609is defined; thus, a mutable object such as a list or dictionary used
610as default value will be shared by all calls that don't specify an
611argument value for the corresponding slot; this should usually be
612avoided.) If there are any unfilled slots for which no default value
613is specified, a \exception{TypeError} exception is raised. Otherwise,
614the list of filled slots is used as the argument list for the call.
615
616If there are more positional arguments than there are formal parameter
617slots, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000618parameter using the syntax \samp{*identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000619case, that formal parameter receives a tuple containing the excess
620positional arguments (or an empty tuple if there were no excess
621positional arguments).
622
623If any keyword argument does not correspond to a formal parameter
624name, a \exception{TypeError} exception is raised, unless a formal
Fred Drakeea81edf1998-11-25 17:51:15 +0000625parameter using the syntax \samp{**identifier} is present; in this
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000626case, that formal parameter receives a dictionary containing the
627excess keyword arguments (using the keywords as keys and the argument
628values as corresponding values), or a (new) empty dictionary if there
629were no excess keyword arguments.
630
Michael W. Hudson850d3982001-12-12 11:56:33 +0000631If the syntax \samp{*expression} appears in the function call,
632\samp{expression} must evaluate to a sequence. Elements from this
633sequence are treated as if they were additional positional arguments;
634if there are postional arguments \var{x1},...,\var{xN} , and
635\samp{expression} evaluates to a sequence \var{y1},...,\var{yM}, this
636is equivalent to a call with M+N positional arguments
637\var{x1},...,\var{xN},\var{y1},...,\var{yM}.
638
639A consequence of this is that although the \samp{*expression} syntax
640appears \emph{after} any keyword arguments, it is processed
Fred Drakeb062cb22001-12-14 16:57:31 +0000641\emph{before} the keyword arguments (and the
642\samp{**expression} argument, if any -- see below). So:
Michael W. Hudson850d3982001-12-12 11:56:33 +0000643
644\begin{verbatim}
645>>> def f(a, b):
646... print a, b
647...
648>>> f(b=1, *(2,))
6492 1
650>>> f(a=1, *(2,))
651Traceback (most recent call last):
652 File "<stdin>", line 1, in ?
653TypeError: f() got multiple values for keyword argument 'a'
654>>> f(1, *(2,))
6551 2
656\end{verbatim}
657
Fred Drakeb062cb22001-12-14 16:57:31 +0000658It is unusual for both keyword arguments and the
659\samp{*expression} syntax to be used in the same call, so in practice
660this confusion does not arise.
Michael W. Hudson850d3982001-12-12 11:56:33 +0000661
662If the syntax \samp{**expression} appears in the function call,
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000663\samp{expression} must evaluate to a mapping, the
Michael W. Hudson850d3982001-12-12 11:56:33 +0000664contents of which are treated as additional keyword arguments. In the
665case of a keyword appearing in both \samp{expression} and as an
666explicit keyword argument, a \exception{TypeError} exception is
667raised.
668
Fred Drakeea81edf1998-11-25 17:51:15 +0000669Formal parameters using the syntax \samp{*identifier} or
670\samp{**identifier} cannot be used as positional argument slots or
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000671as keyword argument names.
Fred Drakef6669171998-05-06 19:52:49 +0000672
Fred Drake5c07d9b1998-05-14 19:37:06 +0000673A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000674raises an exception. How this value is computed depends on the type
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000675of the callable object.
676
677If it is---
Fred Drakef6669171998-05-06 19:52:49 +0000678
679\begin{description}
680
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000681\item[a user-defined function:] The code block for the function is
Fred Drakef6669171998-05-06 19:52:49 +0000682executed, passing it the argument list. The first thing the code
683block will do is bind the formal parameters to the arguments; this is
684described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000685\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000686function call.
687\indexii{function}{call}
688\indexiii{user-defined}{function}{call}
689\obindex{user-defined function}
690\obindex{function}
691
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000692\item[a built-in function or method:] The result is up to the
Fred Drake3d83fc32000-07-31 20:08:23 +0000693interpreter; see the \citetitle[../lib/built-in-funcs.html]{Python
694Library Reference} for the descriptions of built-in functions and
695methods.
Fred Drakef6669171998-05-06 19:52:49 +0000696\indexii{function}{call}
697\indexii{built-in function}{call}
698\indexii{method}{call}
699\indexii{built-in method}{call}
700\obindex{built-in method}
701\obindex{built-in function}
702\obindex{method}
703\obindex{function}
704
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000705\item[a class object:] A new instance of that class is returned.
Fred Drakef6669171998-05-06 19:52:49 +0000706\obindex{class}
707\indexii{class object}{call}
708
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000709\item[a class instance method:] The corresponding user-defined
Fred Drakef6669171998-05-06 19:52:49 +0000710function is called, with an argument list that is one longer than the
711argument list of the call: the instance becomes the first argument.
712\obindex{class instance}
713\obindex{instance}
Fred Drakef6669171998-05-06 19:52:49 +0000714\indexii{class instance}{call}
715
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000716\item[a class instance:] The class must define a \method{__call__()}
717method; the effect is then the same as if that method was called.
718\indexii{instance}{call}
Fred Drakeea81edf1998-11-25 17:51:15 +0000719\withsubitem{(object method)}{\ttindex{__call__()}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000720
Fred Drakef6669171998-05-06 19:52:49 +0000721\end{description}
722
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000723
Fred Drake020f8c01998-07-28 19:32:59 +0000724\section{The power operator\label{power}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000725
726The power operator binds more tightly than unary operators on its
727left; it binds less tightly than unary operators on its right. The
728syntax is:
729
Fred Drakecb4638a2001-07-06 22:49:53 +0000730\begin{productionlist}
731 \production{power}
732 {\token{primary} ["**" \token{u_expr}]}
733\end{productionlist}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000734
735Thus, in an unparenthesized sequence of power and unary operators, the
736operators are evaluated from right to left (this does not constrain
737the evaluation order for the operands).
738
739The power operator has the same semantics as the built-in
740\function{pow()} function, when called with two arguments: it yields
741its left argument raised to the power of its right argument. The
742numeric arguments are first converted to a common type. The result
Raymond Hettinger0da7f392002-11-08 05:30:23 +0000743type is that of the arguments after coercion.
744
745With mixed operand types, the coercion rules for binary arithmetic
746operators apply. For int and long int operands, the result has the
747same type as the operands (after coercion) unless the second argument
748is negative; in that case, all arguments are converted to float and a
749float result is delivered. For example, \code{10**2} returns \code{100},
750but \code{10**-2} returns \code{0.01}. (This last feature was added in
751Python 2.2. In Python 2.1 and before, if both arguments were of integer
752types and the second argument was negative, an exception was raised).
753
754Raising \code{0.0} to a negative power results in a
755\exception{ZeroDivisionError}. Raising a negative number to a
756fractional power results in a \exception{ValueError}.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000757
758
Fred Drakee15956b2000-04-03 04:51:13 +0000759\section{Unary arithmetic operations \label{unary}}
Fred Drakef6669171998-05-06 19:52:49 +0000760\indexiii{unary}{arithmetic}{operation}
761\indexiii{unary}{bit-wise}{operation}
762
763All unary arithmetic (and bit-wise) operations have the same priority:
764
Fred Drakecb4638a2001-07-06 22:49:53 +0000765\begin{productionlist}
766 \production{u_expr}
767 {\token{power} | "-" \token{u_expr}
Fred Drakef6eafc32002-03-18 16:47:14 +0000768 | "+" \token{u_expr} | "{\~}" \token{u_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000769\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000770
Fred Drake5c07d9b1998-05-14 19:37:06 +0000771The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000772numeric argument.
773\index{negation}
774\index{minus}
775
Fred Drake5c07d9b1998-05-14 19:37:06 +0000776The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000777unchanged.
778\index{plus}
779
Fred Drakee15956b2000-04-03 04:51:13 +0000780The unary \code{\~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000781of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000782\code{x} is defined as \code{-(x+1)}. It only applies to integral
783numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000784\index{inversion}
785
786In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000787a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000788\exindex{TypeError}
789
Fred Drake2829f1c2001-06-23 05:27:20 +0000790
Fred Drake020f8c01998-07-28 19:32:59 +0000791\section{Binary arithmetic operations\label{binary}}
Fred Drakef6669171998-05-06 19:52:49 +0000792\indexiii{binary}{arithmetic}{operation}
793
794The binary arithmetic operations have the conventional priority
795levels. Note that some of these operations also apply to certain
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000796non-numeric types. Apart from the power operator, there are only two
797levels, one for multiplicative operators and one for additive
Fred Drakef6669171998-05-06 19:52:49 +0000798operators:
799
Fred Drakecb4638a2001-07-06 22:49:53 +0000800\begin{productionlist}
801 \production{m_expr}
802 {\token{u_expr} | \token{m_expr} "*" \token{u_expr}
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000803 | \token{m_expr} "//" \token{u_expr}
Fred Drake53815882002-03-15 23:21:37 +0000804 | \token{m_expr} "/" \token{u_expr}}
805 \productioncont{| \token{m_expr} "\%" \token{u_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000806 \production{a_expr}
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000807 {\token{m_expr} | \token{a_expr} "+" \token{m_expr}
808 | \token{a_expr} "-" \token{m_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000809\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000810
Fred Drake5c07d9b1998-05-14 19:37:06 +0000811The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000812arguments. The arguments must either both be numbers, or one argument
Fred Drakec3b18d72000-12-07 04:54:02 +0000813must be an integer (plain or long) and the other must be a sequence.
814In the former case, the numbers are converted to a common type and
815then multiplied together. In the latter case, sequence repetition is
Fred Drakef6669171998-05-06 19:52:49 +0000816performed; a negative repetition factor yields an empty sequence.
817\index{multiplication}
818
Fred Drakeaf93c4c2002-04-30 02:18:51 +0000819The \code{/} (division) and \code{//} (floor division) operators yield
820the quotient of their arguments. The numeric arguments are first
821converted to a common type. Plain or long integer division yields an
822integer of the same type; the result is that of mathematical division
823with the `floor' function applied to the result. Division by zero
824raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000825\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000826\exindex{ZeroDivisionError}
827\index{division}
828
Fred Drake5c07d9b1998-05-14 19:37:06 +0000829The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000830division of the first argument by the second. The numeric arguments
831are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000832the \exception{ZeroDivisionError} exception. The arguments may be floating
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000833point numbers, e.g., \code{3.14\%0.7} equals \code{0.34} (since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000834\code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
835yields a result with the same sign as its second operand (or zero);
Tim Peters5b21df42002-11-24 20:23:04 +0000836the absolute value of the result is strictly smaller than the absolute
837value of the second operand\footnote{
Gustavo Niemeyerf9554122002-11-26 18:14:35 +0000838 While \code{abs(x\%y) < abs(y)} is true mathematically, for
Tim Peters5b21df42002-11-24 20:23:04 +0000839 floats it may not be true numerically due to roundoff. For
840 example, and assuming a platform on which a Python float is an
841 IEEE 754 double-precision number, in order that \code{-1e-100 \% 1e100}
842 have the same sign as \code{1e100}, the computed result is
843 \code{-1e-100 + 1e100}, which is numerically exactly equal
844 to \code{1e100}. Function \function{fmod()} in the \module{math}
845 module returns a result whose sign matches the sign of the
846 first argument instead, and so returns \code{-1e-100} in this case.
847 Which approach is more appropriate depends on the application.
848}.
Fred Drakef6669171998-05-06 19:52:49 +0000849\index{modulo}
850
851The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000852following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
853modulo are also connected with the built-in function \function{divmod()}:
854\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Raymond Hettinger6cf09f02002-05-21 18:19:49 +0000855floating point numbers; there similar identities hold
Raymond Hettingerdaa34042003-06-26 17:41:40 +0000856approximately where \code{x/y} is replaced by \code{floor(x/y)} or
Tim Peters5b21df42002-11-24 20:23:04 +0000857\code{floor(x/y) - 1}\footnote{
Fred Drake1ea7c751999-05-06 14:46:35 +0000858 If x is very close to an exact integer multiple of y, it's
859 possible for \code{floor(x/y)} to be one larger than
860 \code{(x-x\%y)/y} due to rounding. In such cases, Python returns
861 the latter result, in order to preserve that \code{divmod(x,y)[0]
862 * y + x \%{} y} be very close to \code{x}.
Raymond Hettinger6cf09f02002-05-21 18:19:49 +0000863}.
864
Georg Brandlc47f1c12005-12-26 23:15:48 +0000865In addition to performing the modulo operation on numbers, the \code{\%}
866operator is also overloaded by string and unicode objects to perform
867string formatting (also known as interpolation). The syntax for string
Georg Brandl5f0ff5c2006-01-20 17:51:37 +0000868formatting is described in the
869\citetitle[../lib/typesseq-strings.html]{Python Library Reference},
870section ``Sequence Types''.
Georg Brandlc47f1c12005-12-26 23:15:48 +0000871
Raymond Hettinger463bfaf2002-10-11 21:08:02 +0000872\deprecated{2.3}{The floor division operator, the modulo operator,
873and the \function{divmod()} function are no longer defined for complex
874numbers. Instead, convert to a floating point number using the
875\function{abs()} function if appropriate.}
Fred Drakef6669171998-05-06 19:52:49 +0000876
Fred Drake5c07d9b1998-05-14 19:37:06 +0000877The \code{+} (addition) operator yields the sum of its arguments.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000878The arguments must either both be numbers or both sequences of the
Fred Drakef6669171998-05-06 19:52:49 +0000879same type. In the former case, the numbers are converted to a common
880type and then added together. In the latter case, the sequences are
881concatenated.
882\index{addition}
883
Fred Drake5c07d9b1998-05-14 19:37:06 +0000884The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000885arguments. The numeric arguments are first converted to a common
886type.
887\index{subtraction}
888
Fred Drake2829f1c2001-06-23 05:27:20 +0000889
Fred Drake020f8c01998-07-28 19:32:59 +0000890\section{Shifting operations\label{shifting}}
Fred Drakef6669171998-05-06 19:52:49 +0000891\indexii{shifting}{operation}
892
893The shifting operations have lower priority than the arithmetic
894operations:
895
Fred Drakecb4638a2001-07-06 22:49:53 +0000896\begin{productionlist}
897 \production{shift_expr}
898 {\token{a_expr}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000899 | \token{shift_expr} ( "<<" | ">>" ) \token{a_expr}}
Fred Drakecb4638a2001-07-06 22:49:53 +0000900\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000901
902These operators accept plain or long integers as arguments. The
903arguments are converted to a common type. They shift the first
904argument to the left or right by the number of bits given by the
905second argument.
906
907A right shift by \var{n} bits is defined as division by
908\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
909multiplication with \code{pow(2,\var{n})}; for plain integers there is
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000910no overflow check so in that case the operation drops bits and flips
911the sign if the result is not less than \code{pow(2,31)} in absolute
912value. Negative shift counts raise a \exception{ValueError}
913exception.
Fred Drakef6669171998-05-06 19:52:49 +0000914\exindex{ValueError}
915
Fred Drake2829f1c2001-06-23 05:27:20 +0000916
Fred Drake020f8c01998-07-28 19:32:59 +0000917\section{Binary bit-wise operations\label{bitwise}}
Fred Drakef6669171998-05-06 19:52:49 +0000918\indexiii{binary}{bit-wise}{operation}
919
920Each of the three bitwise operations has a different priority level:
921
Fred Drakecb4638a2001-07-06 22:49:53 +0000922\begin{productionlist}
923 \production{and_expr}
924 {\token{shift_expr} | \token{and_expr} "\&" \token{shift_expr}}
925 \production{xor_expr}
926 {\token{and_expr} | \token{xor_expr} "\textasciicircum" \token{and_expr}}
927 \production{or_expr}
928 {\token{xor_expr} | \token{or_expr} "|" \token{xor_expr}}
929\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000930
Fred Drake5c07d9b1998-05-14 19:37:06 +0000931The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000932must be plain or long integers. The arguments are converted to a
933common type.
934\indexii{bit-wise}{and}
935
Fred Drake5c07d9b1998-05-14 19:37:06 +0000936The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000937arguments, which must be plain or long integers. The arguments are
938converted to a common type.
939\indexii{bit-wise}{xor}
940\indexii{exclusive}{or}
941
Fred Drake5c07d9b1998-05-14 19:37:06 +0000942The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000943arguments, which must be plain or long integers. The arguments are
944converted to a common type.
945\indexii{bit-wise}{or}
946\indexii{inclusive}{or}
947
Fred Drake2829f1c2001-06-23 05:27:20 +0000948
Fred Drake020f8c01998-07-28 19:32:59 +0000949\section{Comparisons\label{comparisons}}
Fred Drakef6669171998-05-06 19:52:49 +0000950\index{comparison}
951
Fred Drake1156f622000-09-19 18:10:05 +0000952Unlike C, all comparison operations in Python have the same priority,
953which is lower than that of any arithmetic, shifting or bitwise
954operation. Also unlike C, expressions like \code{a < b < c} have the
955interpretation that is conventional in mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000956\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000957
Fred Drakecb4638a2001-07-06 22:49:53 +0000958\begin{productionlist}
959 \production{comparison}
960 {\token{or_expr} ( \token{comp_operator} \token{or_expr} )*}
961 \production{comp_operator}
Neal Norwitz3bd844e2006-08-29 04:39:12 +0000962 {"<" | ">" | "==" | ">=" | "<=" | "!="}
Fred Drake53815882002-03-15 23:21:37 +0000963 \productioncont{| "is" ["not"] | ["not"] "in"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000964\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000965
Raymond Hettingerb268f032003-06-06 02:52:14 +0000966Comparisons yield boolean values: \code{True} or \code{False}.
Fred Drakef6669171998-05-06 19:52:49 +0000967
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000968Comparisons can be chained arbitrarily, e.g., \code{x < y <= z} is
Fred Drakef6669171998-05-06 19:52:49 +0000969equivalent to \code{x < y and y <= z}, except that \code{y} is
970evaluated only once (but in both cases \code{z} is not evaluated at all
971when \code{x < y} is found to be false).
972\indexii{chaining}{comparisons}
973
974Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
975expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
976operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000977to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
Fred Drakef6669171998-05-06 19:52:49 +0000978\var{y opy z}, except that each expression is evaluated at most once.
979
980Note that \var{a opa b opb c} doesn't imply any kind of comparison
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000981between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
Fred Drakef6669171998-05-06 19:52:49 +0000982perfectly legal (though perhaps not pretty).
983
Fred Drake1156f622000-09-19 18:10:05 +0000984The operators \code{<}, \code{>}, \code{==}, \code{>=}, \code{<=}, and
985\code{!=} compare
986the values of two objects. The objects need not have the same type.
Fred Drakefd867712002-04-09 14:39:10 +0000987If both are numbers, they are converted to a common type. Otherwise,
Fred Drake9ad9c9b1998-07-27 20:27:53 +0000988objects of different types \emph{always} compare unequal, and are
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000989ordered consistently but arbitrarily. You can control comparison
990behavior of objects of non-builtin types by defining a \code{__cmp__}
991method or rich comparison methods like \code{__gt__}, described in
992section~\ref{specialnames}.
Fred Drakef6669171998-05-06 19:52:49 +0000993
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000994(This unusual definition of comparison was used to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000995definition of operations like sorting and the \keyword{in} and
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000996\keyword{not in} operators. In the future, the comparison rules for
997objects of different types are likely to change.)
Fred Drakef6669171998-05-06 19:52:49 +0000998
999Comparison of objects of the same type depends on the type:
1000
1001\begin{itemize}
1002
1003\item
1004Numbers are compared arithmetically.
1005
1006\item
1007Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +00001008(the result of the built-in function \function{ord()}) of their
Fred Drake1156f622000-09-19 18:10:05 +00001009characters. Unicode and 8-bit strings are fully interoperable in this
1010behavior.
Fred Drakef6669171998-05-06 19:52:49 +00001011
1012\item
1013Tuples and lists are compared lexicographically using comparison of
Raymond Hettingerdaa34042003-06-26 17:41:40 +00001014corresponding elements. This means that to compare equal, each
1015element must compare equal and the two sequences must be of the same
1016type and have the same length.
1017
1018If not equal, the sequences are ordered the same as their first
1019differing elements. For example, \code{cmp([1,2,x], [1,2,y])} returns
1020the same as \code{cmp(x,y)}. If the corresponding element does not
1021exist, the shorter sequence is ordered first (for example,
1022\code{[1,2] < [1,2,3]}).
Fred Drakef6669171998-05-06 19:52:49 +00001023
1024\item
Tim Peters20524db2001-10-01 20:22:45 +00001025Mappings (dictionaries) compare equal if and only if their sorted
1026(key, value) lists compare equal.\footnote{The implementation computes
1027 this efficiently, without constructing lists or sorting.}
1028Outcomes other than equality are resolved consistently, but are not
Tim Peters1350c072001-10-01 20:25:26 +00001029otherwise defined.\footnote{Earlier versions of Python used
Tim Peters20524db2001-10-01 20:22:45 +00001030 lexicographic comparison of the sorted (key, value) lists, but this
1031 was very expensive for the common case of comparing for equality. An
1032 even earlier version of Python compared dictionaries by identity only,
1033 but this caused surprises because people expected to be able to test
1034 a dictionary for emptiness by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +00001035
1036\item
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001037Most other objects of builtin types compare unequal unless they are
1038the same object;
Fred Drakef6669171998-05-06 19:52:49 +00001039the choice whether one object is considered smaller or larger than
1040another one is made arbitrarily but consistently within one
1041execution of a program.
1042
1043\end{itemize}
1044
Fred Drake7399b9e2000-07-11 19:43:47 +00001045The operators \keyword{in} and \keyword{not in} test for set
Fred Drakeac79e952001-03-06 07:32:11 +00001046membership. \code{\var{x} in \var{s}} evaluates to true if \var{x}
1047is a member of the set \var{s}, and false otherwise. \code{\var{x}
1048not in \var{s}} returns the negation of \code{\var{x} in \var{s}}.
1049The set membership test has traditionally been bound to sequences; an
1050object is a member of a set if the set is a sequence and contains an
1051element equal to that object. However, it is possible for an object
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001052to support membership tests without being a sequence. In particular,
Fred Drakeb184ae82005-01-19 03:39:17 +00001053dictionaries support membership testing as a nicer way of spelling
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +00001054\code{\var{key} in \var{dict}}; other mapping types may follow suit.
Fred Drake7399b9e2000-07-11 19:43:47 +00001055
Fred Drake34bafcc2001-01-14 02:57:14 +00001056For the list and tuple types, \code{\var{x} in \var{y}} is true if and
Fred Drakeac79e952001-03-06 07:32:11 +00001057only if there exists an index \var{i} such that
Fred Drake34bafcc2001-01-14 02:57:14 +00001058\code{\var{x} == \var{y}[\var{i}]} is true.
Fred Drake7399b9e2000-07-11 19:43:47 +00001059
Fred Drake1156f622000-09-19 18:10:05 +00001060For the Unicode and string types, \code{\var{x} in \var{y}} is true if
Raymond Hettingerd0cda1d2003-06-26 19:32:10 +00001061and only if \var{x} is a substring of \var{y}. An equivalent test is
1062\code{y.find(x) != -1}. Note, \var{x} and \var{y} need not be the
1063same type; consequently, \code{u'ab' in 'abc'} will return \code{True}.
1064Empty strings are always considered to be a substring of any other string,
1065so \code{"" in "abc"} will return \code{True}.
1066\versionchanged[Previously, \var{x} was required to be a string of
1067length \code{1}]{2.3}
Fred Drake7399b9e2000-07-11 19:43:47 +00001068
1069For user-defined classes which define the \method{__contains__()} method,
1070\code{\var{x} in \var{y}} is true if and only if
1071\code{\var{y}.__contains__(\var{x})} is true.
1072
1073For user-defined classes which do not define \method{__contains__()} and
Fred Drake1156f622000-09-19 18:10:05 +00001074do define \method{__getitem__()}, \code{\var{x} in \var{y}} is true if
1075and only if there is a non-negative integer index \var{i} such that
Fred Drake7399b9e2000-07-11 19:43:47 +00001076\code{\var{x} == \var{y}[\var{i}]}, and all lower integer indices
1077do not raise \exception{IndexError} exception. (If any other exception
1078is raised, it is as if \keyword{in} raised that exception).
1079
1080The operator \keyword{not in} is defined to have the inverse true value
1081of \keyword{in}.
Fred Drakef6669171998-05-06 19:52:49 +00001082\opindex{in}
1083\opindex{not in}
1084\indexii{membership}{test}
1085\obindex{sequence}
1086
Fred Drake5c07d9b1998-05-14 19:37:06 +00001087The operators \keyword{is} and \keyword{is not} test for object identity:
1088\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
1089are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +00001090truth value.
1091\opindex{is}
1092\opindex{is not}
1093\indexii{identity}{test}
1094
Fred Drake2829f1c2001-06-23 05:27:20 +00001095
Fred Drake020f8c01998-07-28 19:32:59 +00001096\section{Boolean operations\label{Booleans}}
Guido van Rossumd8faa362007-04-27 19:54:29 +00001097\indexii{Conditional}{expression}
Fred Drakef6669171998-05-06 19:52:49 +00001098\indexii{Boolean}{operation}
1099
1100Boolean operations have the lowest priority of all Python operations:
1101
Fred Drakecb4638a2001-07-06 22:49:53 +00001102\begin{productionlist}
1103 \production{expression}
Guido van Rossumd8faa362007-04-27 19:54:29 +00001104 {\token{conditional_expression} | \token{lambda_form}}
1105 \production{old_expression}
1106 {\token{or_test} | \token{old_lambda_form}}
1107 \production{conditional_expression}
1108 {\token{or_test} ["if" \token{or_test} "else" \token{expression}]}
Fred Drakecb4638a2001-07-06 22:49:53 +00001109 \production{or_test}
1110 {\token{and_test} | \token{or_test} "or" \token{and_test}}
1111 \production{and_test}
1112 {\token{not_test} | \token{and_test} "and" \token{not_test}}
1113 \production{not_test}
1114 {\token{comparison} | "not" \token{not_test}}
Fred Drakecb4638a2001-07-06 22:49:53 +00001115\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +00001116
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001117In the context of Boolean operations, and also when expressions are
Fred Drakef6669171998-05-06 19:52:49 +00001118used by control flow statements, the following values are interpreted
Georg Brandl6cd53772005-08-21 12:22:58 +00001119as false: \code{False}, \code{None}, numeric zero of all types, and empty
1120strings and containers (including strings, tuples, lists, dictionaries,
1121sets and frozensets). All other values are interpreted as true.
Fred Drakef6669171998-05-06 19:52:49 +00001122
Raymond Hettinger46a16f22004-04-23 17:11:47 +00001123The operator \keyword{not} yields \code{True} if its argument is false,
1124\code{False} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +00001125\opindex{not}
1126
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001127The expression \code{\var{x} if \var{C} else \var{y}} first evaluates
1128\var{C} (\emph{not} \var{x}); if \var{C} is true, \var{x} is evaluated and
1129its value is returned; otherwise, \var{y} is evaluated and its value is
Neal Norwitzf9f61b42006-02-27 16:31:12 +00001130returned. \versionadded{2.5}
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00001131
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001132The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +00001133\var{x} is false, its value is returned; otherwise, \var{y} is
1134evaluated and the resulting value is returned.
1135\opindex{and}
1136
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001137The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +00001138\var{x} is true, its value is returned; otherwise, \var{y} is
1139evaluated and the resulting value is returned.
1140\opindex{or}
1141
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001142(Note that neither \keyword{and} nor \keyword{or} restrict the value
Raymond Hettinger46a16f22004-04-23 17:11:47 +00001143and type they return to \code{False} and \code{True}, but rather return the
Fred Drake5c07d9b1998-05-14 19:37:06 +00001144last evaluated argument.
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001145This is sometimes useful, e.g., if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +00001146replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +00001147\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +00001148invent a value anyway, it does not bother to return a value of the
Raymond Hettinger46a16f22004-04-23 17:11:47 +00001149same type as its argument, so e.g., \code{not 'foo'} yields \code{False},
Fred Drake5c07d9b1998-05-14 19:37:06 +00001150not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +00001151
Jeremy Hylton2225add2002-04-01 21:05:21 +00001152\section{Lambdas\label{lambdas}}
1153\indexii{lambda}{expression}
1154\indexii{lambda}{form}
Martin v. Löwis95cf84a2003-10-19 07:32:24 +00001155\indexii{anonymous}{function}
Jeremy Hylton2225add2002-04-01 21:05:21 +00001156
Martin v. Löwis477c8562004-06-02 12:54:33 +00001157\begin{productionlist}
1158 \production{lambda_form}
1159 {"lambda" [\token{parameter_list}]: \token{expression}}
Guido van Rossumd8faa362007-04-27 19:54:29 +00001160 \production{old_lambda_form}
1161 {"lambda" [\token{parameter_list}]: \token{old_expression}}
Martin v. Löwis477c8562004-06-02 12:54:33 +00001162\end{productionlist}
1163
Fred Drakef6669171998-05-06 19:52:49 +00001164Lambda forms (lambda expressions) have the same syntactic position as
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001165expressions. They are a shorthand to create anonymous functions; the
1166expression \code{lambda \var{arguments}: \var{expression}}
Jeremy Hylton2225add2002-04-01 21:05:21 +00001167yields a function object. The unnamed object behaves like a function
Raymond Hettinger7fd9ced2002-06-25 04:04:14 +00001168object defined with
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001169
1170\begin{verbatim}
1171def name(arguments):
1172 return expression
1173\end{verbatim}
1174
1175See section \ref{function} for the syntax of parameter lists. Note
Guido van Rossum1bc535d2007-05-15 18:46:22 +00001176that functions created with lambda forms cannot contain statements
1177or annotations.
Fred Drakef6669171998-05-06 19:52:49 +00001178\label{lambda}
Fred Drake88382692001-06-05 02:17:02 +00001179
Fred Drake020f8c01998-07-28 19:32:59 +00001180\section{Expression lists\label{exprlists}}
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001181\indexii{expression}{list}
Fred Drakef6669171998-05-06 19:52:49 +00001182
Fred Drakecb4638a2001-07-06 22:49:53 +00001183\begin{productionlist}
1184 \production{expression_list}
1185 {\token{expression} ( "," \token{expression} )* [","]}
1186\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +00001187
Fred Drakec009d192000-04-25 21:09:10 +00001188An expression list containing at least one comma yields a
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001189tuple. The length of the tuple is the number of expressions in the
1190list. The expressions are evaluated from left to right.
Fred Drakef6669171998-05-06 19:52:49 +00001191\obindex{tuple}
1192
1193The trailing comma is required only to create a single tuple (a.k.a. a
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001194\emph{singleton}); it is optional in all other cases. A single
Fred Drakec009d192000-04-25 21:09:10 +00001195expression without a trailing comma doesn't create a
1196tuple, but rather yields the value of that expression.
Fred Drakef6669171998-05-06 19:52:49 +00001197(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +00001198\code{()}.)
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001199\indexii{trailing}{comma}
Fred Drakef6669171998-05-06 19:52:49 +00001200
Gustavo Niemeyer78429a62002-12-16 13:54:02 +00001201\section{Evaluation order\label{evalorder}}
1202\indexii{evaluation}{order}
1203
1204Python evaluates expressions from left to right. Notice that while
1205evaluating an assignment, the right-hand side is evaluated before
1206the left-hand side.
1207
1208In the following lines, expressions will be evaluated in the
1209arithmetic order of their suffixes:
1210
1211\begin{verbatim}
1212expr1, expr2, expr3, expr4
1213(expr1, expr2, expr3, expr4)
1214{expr1: expr2, expr3: expr4}
1215expr1 + expr2 * (expr3 - expr4)
1216func(expr1, expr2, *expr3, **expr4)
1217expr3, expr4 = expr1, expr2
1218\end{verbatim}
Fred Draked09120b1999-04-29 16:43:42 +00001219
Fred Drake020f8c01998-07-28 19:32:59 +00001220\section{Summary\label{summary}}
Fred Drakef6669171998-05-06 19:52:49 +00001221
Fred Draked09120b1999-04-29 16:43:42 +00001222The following table summarizes the operator
1223precedences\indexii{operator}{precedence} in Python, from lowest
1224precedence (least binding) to highest precedence (most binding).
1225Operators in the same box have the same precedence. Unless the syntax
1226is explicitly given, operators are binary. Operators in the same box
Alex Martellic516b0e2003-11-09 16:33:56 +00001227group left to right (except for comparisons, including tests, which all
1228have the same precedence and chain from left to right --- see section
1229\ref{comparisons} -- and exponentiation, which groups from right to left).
Fred Drakef6669171998-05-06 19:52:49 +00001230
Fred Draked09120b1999-04-29 16:43:42 +00001231\begin{tableii}{c|l}{textrm}{Operator}{Description}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001232 \lineii{\keyword{lambda}} {Lambda expression}
1233 \hline
1234 \lineii{\keyword{or}} {Boolean OR}
1235 \hline
1236 \lineii{\keyword{and}} {Boolean AND}
1237 \hline
1238 \lineii{\keyword{not} \var{x}} {Boolean NOT}
1239 \hline
1240 \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests}
1241 \lineii{\keyword{is}, \keyword{is not}}{Identity tests}
1242 \lineii{\code{<}, \code{<=}, \code{>}, \code{>=},
Neal Norwitz3bd844e2006-08-29 04:39:12 +00001243 \code{!=}, \code{==}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001244 {Comparisons}
1245 \hline
1246 \lineii{\code{|}} {Bitwise OR}
1247 \hline
1248 \lineii{\code{\^}} {Bitwise XOR}
1249 \hline
1250 \lineii{\code{\&}} {Bitwise AND}
1251 \hline
Thomas Wouters477c8d52006-05-27 19:21:47 +00001252 \lineii{\code{<<}, \code{>>}} {Shifts}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001253 \hline
1254 \lineii{\code{+}, \code{-}}{Addition and subtraction}
1255 \hline
Fred Drake9beee801998-10-21 00:44:49 +00001256 \lineii{\code{*}, \code{/}, \code{\%}}
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001257 {Multiplication, division, remainder}
1258 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001259 \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
1260 \lineii{\code{\~\var{x}}} {Bitwise not}
1261 \hline
Fred Drakeb8ac0092001-05-09 16:51:49 +00001262 \lineii{\code{**}} {Exponentiation}
1263 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001264 \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
1265 \lineii{\code{\var{x}[\var{index}]}} {Subscription}
1266 \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
1267 \lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
Fred Draked09120b1999-04-29 16:43:42 +00001268 \hline
Fred Drake9ad9c9b1998-07-27 20:27:53 +00001269 \lineii{\code{(\var{expressions}\ldots)}} {Binding or tuple display}
1270 \lineii{\code{[\var{expressions}\ldots]}} {List display}
1271 \lineii{\code{\{\var{key}:\var{datum}\ldots\}}}{Dictionary display}
1272 \lineii{\code{`\var{expressions}\ldots`}} {String conversion}
1273\end{tableii}