blob: d0d57ec00110a82369d70c1dfc76ee5ef3bc8049 [file] [log] [blame]
Guido van Rossum3a0ad601998-07-23 21:57:42 +00001\chapter{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
11\begin{verbatim}
12name: othername
13\end{verbatim}
14
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
19\section{Arithmetic conversions}
20\indexii{arithmetic}{conversion}
21
22When a description of an arithmetic operator below uses the phrase
Guido van Rossum3a0ad601998-07-23 21:57:42 +000023``the numeric arguments are converted to a common type,'' the
24arguments are coerced using the coercion rules listed at the end of
25chapter 3. If both arguments are standard numeric types, the
26following coercions are applied:
Fred Drakef6669171998-05-06 19:52:49 +000027
28\begin{itemize}
Guido van Rossum3a0ad601998-07-23 21:57:42 +000029\item If either argument is a complex number, the other is converted
30 to complex;
31\item otherwise, if either argument is a floating point number,
Fred Drakef6669171998-05-06 19:52:49 +000032 the other is converted to floating point;
Guido van Rossum3a0ad601998-07-23 21:57:42 +000033\item otherwise, if either argument is a long integer,
Fred Drakef6669171998-05-06 19:52:49 +000034 the other is converted to long integer;
35\item otherwise, both must be plain integers and no conversion
36 is necessary.
37\end{itemize}
38
Guido van Rossum3a0ad601998-07-23 21:57:42 +000039Some additional rules apply for certain operators (e.g. a string left
40argument to the `\%' operator). Extensions can define their own
41coercions.
Fred Drakef6669171998-05-06 19:52:49 +000042\section{Atoms}
43\index{atom}
44
Guido van Rossum3a0ad601998-07-23 21:57:42 +000045Atoms are the most basic elements of expressions. The simplest atoms
46are identifiers or literals. Forms enclosed in
Fred Drakef6669171998-05-06 19:52:49 +000047reverse quotes or in parentheses, brackets or braces are also
48categorized syntactically as atoms. The syntax for atoms is:
49
50\begin{verbatim}
51atom: identifier | literal | enclosure
52enclosure: parenth_form|list_display|dict_display|string_conversion
53\end{verbatim}
54
55\subsection{Identifiers (Names)}
56\index{name}
57\index{identifier}
58
59An identifier occurring as an atom is a reference to a local, global
60or built-in name binding. If a name is assigned to anywhere in a code
61block (even in unreachable code), and is not mentioned in a
Fred Drake5c07d9b1998-05-14 19:37:06 +000062\keyword{global} statement in that code block, then it refers to a local
Fred Drakef6669171998-05-06 19:52:49 +000063name throughout that code block. When it is not assigned to anywhere
64in the block, or when it is assigned to but also explicitly listed in
Fred Drake5c07d9b1998-05-14 19:37:06 +000065a \keyword{global} statement, it refers to a global name if one exists,
Fred Drakef6669171998-05-06 19:52:49 +000066else to a built-in name (and this binding may dynamically change).
67\indexii{name}{binding}
68\index{code block}
69\stindex{global}
70\indexii{built-in}{name}
71\indexii{global}{name}
72
73When the name is bound to an object, evaluation of the atom yields
74that object. When a name is not bound, an attempt to evaluate it
Fred Drake5c07d9b1998-05-14 19:37:06 +000075raises a \exception{NameError} exception.
Fred Drakef6669171998-05-06 19:52:49 +000076\exindex{NameError}
77
Guido van Rossum3a0ad601998-07-23 21:57:42 +000078\strong{Private name mangling:}%
79\indexii{name}{mangling}%
80\indexii{private}{names}%
81when an identifier that textually occurs in a class definition begins
82with two or more underscore characters and does not end in two or more
83underscores, it is considered a ``private name'' of that class.
84Private names are transformed to a longer form before code is
85generated for them. The transformation inserts the class name in
86front of the name, with leading underscores removed, and a single
87underscore inserted in front of the class name. For example, the
88identifier \code{__spam} occurring in a class named \code{Ham} will be
89transformed to \code{_Ham__spam}. This transformation is independent
90of the syntactical context in which the identifier is used. If the
91transformed name is extremely long (longer than 255 characters),
92implementation defined truncation may happen. If the class name
93consists only of underscores, no transformation is done.
94
Fred Drakef6669171998-05-06 19:52:49 +000095\subsection{Literals}
96\index{literal}
97
Guido van Rossum3a0ad601998-07-23 21:57:42 +000098Python supports string literals and various numeric literals:
Fred Drakef6669171998-05-06 19:52:49 +000099
100\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000101literal: stringliteral | integer | longinteger | floatnumber | imagnumber
Fred Drakef6669171998-05-06 19:52:49 +0000102\end{verbatim}
103
104Evaluation of a literal yields an object of the given type (string,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000105integer, long integer, floating point number, complex number) with the
106given value. The value may be approximated in the case of floating
107point and imaginary (complex) literals. See section \ref{literals}
108for details.
Fred Drakef6669171998-05-06 19:52:49 +0000109
110All literals correspond to immutable data types, and hence the
111object's identity is less important than its value. Multiple
112evaluations of literals with the same value (either the same
113occurrence in the program text or a different occurrence) may obtain
114the same object or a different object with the same value.
115\indexiii{immutable}{data}{type}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000116\indexii{immutable}{objects}
Fred Drakef6669171998-05-06 19:52:49 +0000117
118\subsection{Parenthesized forms}
119\index{parenthesized form}
120
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000121A parenthesized form is an optional expression list enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000122parentheses:
123
124\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000125parenth_form: "(" [expression_list] ")"
Fred Drakef6669171998-05-06 19:52:49 +0000126\end{verbatim}
127
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000128A parenthesized expression list yields whatever that expression list
129yields: if the list contains at least one comma, it yields a tuple;
130otherwise, it yields the single expression that makes up the
131expression list.
Fred Drakef6669171998-05-06 19:52:49 +0000132
133An empty pair of parentheses yields an empty tuple object. Since
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000134tuples are immutable, the rules for literals apply (i.e., two
135occurrences of the empty tuple may or may not yield the same object).
Fred Drakef6669171998-05-06 19:52:49 +0000136\indexii{empty}{tuple}
137
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000138Note that tuples are not formed by the parentheses, but rather by use
Fred Drakef6669171998-05-06 19:52:49 +0000139of the comma operator. The exception is the empty tuple, for which
140parentheses {\em are} required --- allowing unparenthesized ``nothing''
141in expressions would cause ambiguities and allow common typos to
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000142pass uncaught.
Fred Drakef6669171998-05-06 19:52:49 +0000143\index{comma}
144\indexii{tuple}{display}
145
146\subsection{List displays}
147\indexii{list}{display}
148
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000149A list display is a possibly empty series of expressions enclosed in
Fred Drakef6669171998-05-06 19:52:49 +0000150square brackets:
151
152\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000153list_display: "[" [expression_list] "]"
Fred Drakef6669171998-05-06 19:52:49 +0000154\end{verbatim}
155
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000156A list display yields a new list object. If it has no expression
157list, the list object has no items. Otherwise, the elements of the
158expression list are evaluated from left to right and inserted in the
159list object in that order.
Fred Drakef6669171998-05-06 19:52:49 +0000160\obindex{list}
Fred Drakef6669171998-05-06 19:52:49 +0000161\indexii{empty}{list}
162
163\subsection{Dictionary displays} \label{dict}
164\indexii{dictionary}{display}
165
166A dictionary display is a possibly empty series of key/datum pairs
167enclosed in curly braces:
168\index{key}
169\index{datum}
170\index{key/datum pair}
171
172\begin{verbatim}
173dict_display: "{" [key_datum_list] "}"
174key_datum_list: key_datum ("," key_datum)* [","]
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000175key_datum: expression ":" expression
Fred Drakef6669171998-05-06 19:52:49 +0000176\end{verbatim}
177
178A dictionary display yields a new dictionary object.
179\obindex{dictionary}
180
181The key/datum pairs are evaluated from left to right to define the
182entries of the dictionary: each key object is used as a key into the
183dictionary to store the corresponding datum.
184
185Restrictions on the types of the key values are listed earlier in
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000186section \ref{types}. (To summarize,the key type should be hashable,
187which excludes all mutable objects.) Clashes between duplicate keys
188are not detected; the last datum (textually rightmost in the display)
189stored for a given key value prevails.
190\indexii{immutable}{objects}
Fred Drakef6669171998-05-06 19:52:49 +0000191
192\subsection{String conversions}
193\indexii{string}{conversion}
194\indexii{reverse}{quotes}
195\indexii{backward}{quotes}
196\index{back-quotes}
197
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000198A string conversion is an expression list enclosed in reverse (a.k.a.
Fred Drakef6669171998-05-06 19:52:49 +0000199backward) quotes:
200
201\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000202string_conversion: "`" expression_list "`"
Fred Drakef6669171998-05-06 19:52:49 +0000203\end{verbatim}
204
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000205A string conversion evaluates the contained expression list and
Fred Drakef6669171998-05-06 19:52:49 +0000206converts the resulting object into a string according to rules
207specific to its type.
208
Fred Drake5c07d9b1998-05-14 19:37:06 +0000209If the object is a string, a number, \code{None}, or a tuple, list or
Fred Drakef6669171998-05-06 19:52:49 +0000210dictionary containing only objects whose type is one of these, the
211resulting string is a valid Python expression which can be passed to
Fred Drake5c07d9b1998-05-14 19:37:06 +0000212the built-in function \function{eval()} to yield an expression with the
Fred Drakef6669171998-05-06 19:52:49 +0000213same value (or an approximation, if floating point numbers are
214involved).
215
216(In particular, converting a string adds quotes around it and converts
217``funny'' characters to escape sequences that are safe to print.)
218
219It is illegal to attempt to convert recursive objects (e.g. lists or
220dictionaries that contain a reference to themselves, directly or
221indirectly.)
222\obindex{recursive}
223
Fred Drake5c07d9b1998-05-14 19:37:06 +0000224The built-in function \function{repr()} performs exactly the same
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000225conversion in its argument as enclosing it in parentheses and reverse
226quotes does. The built-in function \function{str()} performs a
227similar but more user-friendly conversion.
Fred Drakef6669171998-05-06 19:52:49 +0000228\bifuncindex{repr}
229\bifuncindex{str}
230
231\section{Primaries} \label{primaries}
232\index{primary}
233
234Primaries represent the most tightly bound operations of the language.
235Their syntax is:
236
237\begin{verbatim}
238primary: atom | attributeref | subscription | slicing | call
239\end{verbatim}
240
241\subsection{Attribute references}
242\indexii{attribute}{reference}
243
244An attribute reference is a primary followed by a period and a name:
245
246\begin{verbatim}
247attributeref: primary "." identifier
248\end{verbatim}
249
250The primary must evaluate to an object of a type that supports
251attribute references, e.g. a module or a list. This object is then
252asked to produce the attribute whose name is the identifier. If this
Fred Drake5c07d9b1998-05-14 19:37:06 +0000253attribute is not available, the exception
254\exception{AttributeError}\exindex{AttributeError} is raised.
255Otherwise, the type and value of the object produced is determined by
256the object. Multiple evaluations of the same attribute reference may
257yield different objects.
Fred Drakef6669171998-05-06 19:52:49 +0000258\obindex{module}
259\obindex{list}
260
261\subsection{Subscriptions}
262\index{subscription}
263
264A subscription selects an item of a sequence (string, tuple or list)
265or mapping (dictionary) object:
266\obindex{sequence}
267\obindex{mapping}
268\obindex{string}
269\obindex{tuple}
270\obindex{list}
271\obindex{dictionary}
272\indexii{sequence}{item}
273
274\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000275subscription: primary "[" expression_list "]"
Fred Drakef6669171998-05-06 19:52:49 +0000276\end{verbatim}
277
278The primary must evaluate to an object of a sequence or mapping type.
279
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000280If the primary is a mapping, the expression list must evaluate to an
281object whose value is one of the keys of the mapping, and the
282subscription selects the value in the mapping that corresponds to that
283key. (The expression list is a tuple except if it has exactly one
284item.)
Fred Drakef6669171998-05-06 19:52:49 +0000285
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000286If the primary is a sequence, the expression (list) must evaluate to a
287plain integer. If this value is negative, the length of the sequence
288is added to it (so that, e.g., \code{x[-1]} selects the last item of
289\code{x}.) The resulting value must be a nonnegative integer less
290than the number of items in the sequence, and the subscription selects
291the item whose index is that value (counting from zero).
Fred Drakef6669171998-05-06 19:52:49 +0000292
293A string's items are characters. A character is not a separate data
294type but a string of exactly one character.
295\index{character}
296\indexii{string}{item}
297
298\subsection{Slicings}
299\index{slicing}
300\index{slice}
301
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000302A slicing selects a range of items in a sequence object (e.g., a
303string, tuple or list). Slicings may be used as expressions or as
304targets in assignment or del statements. The syntax for a slicing:
Fred Drakef6669171998-05-06 19:52:49 +0000305\obindex{sequence}
306\obindex{string}
307\obindex{tuple}
308\obindex{list}
309
310\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000311slicing: simple_slicing | extended_slicing
312simple_slicing: primary "[" short_slice "]"
313extended_slicing: primary "[" slice_list "]"
314slice_list: slice_item ("," slice_item)* [","]
315slice_item: expression | proper_slice | ellipsis
316proper_slice: short_slice | long_slice
317short_slice: [lower_bound] ":" [upper_bound]
318long_slice: short_slice ":" [stride]
319lower_bound: expression
320upper_bound: expression
321stride: expression
322ellipsis: "..."
Fred Drakef6669171998-05-06 19:52:49 +0000323\end{verbatim}
324
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000325There is ambiguity in the formal syntax here: anything that looks like
326an expression list also looks like a slice list, so any subscription
327can be interpreted as a slicing. Rather than further complicating the
328syntax, this is disambiguated by defining that in this case the
329interpretation as a subscription takes priority over the
330interpretation as a slicing (this is the case if the slice list
331contains no proper slice nor ellipses). Similarly, when the slice
332list has exactly one short slice and no trailing comma, the
333interpretation as a simple slicing takes priority over that as an
334extended slicing.\indexii{extended}{slicing}
335
336The semantics for a simple slicing are as follows. The primary must
337evaluate to a sequence object. The lower and upper bound expressions,
338if present, must evaluate to plain integers; defaults are zero and the
339sequence's length, respectively. If either bound is negative, the
340sequence's length is added to it. The slicing now selects all items
341with index \var{k} such that
Fred Drakef6669171998-05-06 19:52:49 +0000342\code{\var{i} <= \var{k} < \var{j}} where \var{i}
343and \var{j} are the specified lower and upper bounds. This may be an
344empty sequence. It is not an error if \var{i} or \var{j} lie outside the
345range of valid indexes (such items don't exist so they aren't
346selected).
347
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000348The semantics for an extended slicing are as follows. The primary
349must evaluate to a mapping object, and it is indexed with a key that
350is constructed from the slice list, as follows. If the slice list
351contains at least one comma, the key is a tuple containing the
352conversion of the slice items; otherwise, the conversion of the lone
353slice item is the key. The conversion of a slice item that is an
354expression is that expression. The conversion of an ellipsis slice
355item is the built-in \code{Ellipsis} object. The conversion of a
356proper slice is a slice object (see section \ref{types}) whose
357\code{start}, \code{stop} and \code{step} attributes are the values of
358the expressions given as lower bound, upper bound and stride,
359respectively, substituting \code{None} for missing expressions.
360
Fred Drakef6669171998-05-06 19:52:49 +0000361\subsection{Calls} \label{calls}
362\index{call}
363
364A call calls a callable object (e.g. a function) with a possibly empty
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000365series of arguments:
Fred Drakef6669171998-05-06 19:52:49 +0000366\obindex{callable}
367
368\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000369call: primary "(" [argument_list [","]] ")"
370argument_list: positional_arguments ["," keyword_arguments]
371 | keyword_arguments
372positional_arguments: expression ("," expression)*
373keyword_arguments: keyword_item ("," keyword_item)*
374keyword_item: identifier "=" expression
Fred Drakef6669171998-05-06 19:52:49 +0000375\end{verbatim}
376
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000377A trailing comma may be present after an argument list but does not
378affect the semantics.
379
Fred Drakef6669171998-05-06 19:52:49 +0000380The primary must evaluate to a callable object (user-defined
381functions, built-in functions, methods of built-in objects, class
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000382objects, methods of class instances, and certain class instances
383themselves are callable; extensions may define additional callable
384object types). All argument expressions are evaluated before the call
385is attempted. Please refer to section \ref{function} for the syntax
386of formal parameter lists.
387
388If keyword arguments are present, they are first converted to
389positional arguments, as follows. First, a list of unfilled slots is
390created for the formal parameters. If there are N positional
391arguments, they are placed in the first N slots. Next, for each
392keyword argument, the identifier is used to determine the
393corresponding slot (if the identifier is the same as the first formal
394parameter name, the first slot is used, and so on). If the slot is
395already filled, a \exception{TypeError} exception is raised.
396Otherwise, the value of the argument is placed in the slot, filling it
397(even if the expression is \code{None}, it fills the slot). When all
398arguments have been processed, the slots that are still unfilled are
399filled with the corresponding default value from the function
400definition. (Default values are calculated, once, when the function
401is defined; thus, a mutable object such as a list or dictionary used
402as default value will be shared by all calls that don't specify an
403argument value for the corresponding slot; this should usually be
404avoided.) If there are any unfilled slots for which no default value
405is specified, a \exception{TypeError} exception is raised. Otherwise,
406the list of filled slots is used as the argument list for the call.
407
408If there are more positional arguments than there are formal parameter
409slots, a \exception{TypeError} exception is raised, unless a formal
410parameter using the syntax ``\code{*identifier}'' is present; in this
411case, that formal parameter receives a tuple containing the excess
412positional arguments (or an empty tuple if there were no excess
413positional arguments).
414
415If any keyword argument does not correspond to a formal parameter
416name, a \exception{TypeError} exception is raised, unless a formal
417parameter using the syntax ``\code{**identifier}'' is present; in this
418case, that formal parameter receives a dictionary containing the
419excess keyword arguments (using the keywords as keys and the argument
420values as corresponding values), or a (new) empty dictionary if there
421were no excess keyword arguments.
422
423Formal parameters using the syntax ``\code{*identifier}'' or
424``\code{**identifier}'' cannot be used as positional argument slots or
425as keyword argument names. Formal parameters using the syntax
426``\code{(sublist)}'' cannot be used as keyword argument names; the
427outermost sublist corresponds to a single unnamed argument slot, and
428the argument value is assigned to the sublist using the usual tuple
429assignment rules after all other parameter processing is done.
Fred Drakef6669171998-05-06 19:52:49 +0000430
Fred Drake5c07d9b1998-05-14 19:37:06 +0000431A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000432raises an exception. How this value is computed depends on the type
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000433of the callable object.
434
435If it is---
Fred Drakef6669171998-05-06 19:52:49 +0000436
437\begin{description}
438
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000439\item[a user-defined function:] The code block for the function is
Fred Drakef6669171998-05-06 19:52:49 +0000440executed, passing it the argument list. The first thing the code
441block will do is bind the formal parameters to the arguments; this is
442described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000443\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000444function call.
445\indexii{function}{call}
446\indexiii{user-defined}{function}{call}
447\obindex{user-defined function}
448\obindex{function}
449
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000450\item[a built-in function or method:] The result is up to the
Fred Drakef6669171998-05-06 19:52:49 +0000451interpreter; see the library reference manual for the descriptions of
452built-in functions and methods.
453\indexii{function}{call}
454\indexii{built-in function}{call}
455\indexii{method}{call}
456\indexii{built-in method}{call}
457\obindex{built-in method}
458\obindex{built-in function}
459\obindex{method}
460\obindex{function}
461
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000462\item[a class object:] A new instance of that class is returned.
Fred Drakef6669171998-05-06 19:52:49 +0000463\obindex{class}
464\indexii{class object}{call}
465
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000466\item[a class instance method:] The corresponding user-defined
Fred Drakef6669171998-05-06 19:52:49 +0000467function is called, with an argument list that is one longer than the
468argument list of the call: the instance becomes the first argument.
469\obindex{class instance}
470\obindex{instance}
Fred Drakef6669171998-05-06 19:52:49 +0000471\indexii{class instance}{call}
472
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000473\item[a class instance:] The class must define a \method{__call__()}
474method; the effect is then the same as if that method was called.
475\indexii{instance}{call}
476\ttindex{__call__}
477
Fred Drakef6669171998-05-06 19:52:49 +0000478\end{description}
479
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000480
481\section{The power operator}
482
483The power operator binds more tightly than unary operators on its
484left; it binds less tightly than unary operators on its right. The
485syntax is:
486
487\begin{verbatim}
488power: primary ["**" u_expr]
489\end{verbatim}
490
491Thus, in an unparenthesized sequence of power and unary operators, the
492operators are evaluated from right to left (this does not constrain
493the evaluation order for the operands).
494
495The power operator has the same semantics as the built-in
496\function{pow()} function, when called with two arguments: it yields
497its left argument raised to the power of its right argument. The
498numeric arguments are first converted to a common type. The result
499type is that of the arguments after coercion; if the result is not
500expressible in that type (as in raising an integer to a negative
501power, or a negative floating point number to a broken power), a
502\exception{TypeError} exception is raised.
503
504
Fred Drakef6669171998-05-06 19:52:49 +0000505\section{Unary arithmetic operations}
506\indexiii{unary}{arithmetic}{operation}
507\indexiii{unary}{bit-wise}{operation}
508
509All unary arithmetic (and bit-wise) operations have the same priority:
510
511\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000512u_expr: power | "-" u_expr | "+" u_expr | "~" u_expr
Fred Drakef6669171998-05-06 19:52:49 +0000513\end{verbatim}
514
Fred Drake5c07d9b1998-05-14 19:37:06 +0000515The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000516numeric argument.
517\index{negation}
518\index{minus}
519
Fred Drake5c07d9b1998-05-14 19:37:06 +0000520The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000521unchanged.
522\index{plus}
523
Fred Drake5c07d9b1998-05-14 19:37:06 +0000524The unary \code{~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000525of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000526\code{x} is defined as \code{-(x+1)}. It only applies to integral
527numbers.
Fred Drakef6669171998-05-06 19:52:49 +0000528\index{inversion}
529
530In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000531a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000532\exindex{TypeError}
533
534\section{Binary arithmetic operations}
535\indexiii{binary}{arithmetic}{operation}
536
537The binary arithmetic operations have the conventional priority
538levels. Note that some of these operations also apply to certain
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000539non-numeric types. Apart from the power operator, there are only two
540levels, one for multiplicative operators and one for additive
Fred Drakef6669171998-05-06 19:52:49 +0000541operators:
542
543\begin{verbatim}
544m_expr: u_expr | m_expr "*" u_expr
545 | m_expr "/" u_expr | m_expr "%" u_expr
546a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
547\end{verbatim}
548
Fred Drake5c07d9b1998-05-14 19:37:06 +0000549The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000550arguments. The arguments must either both be numbers, or one argument
551must be a plain integer and the other must be a sequence. In the
552former case, the numbers are converted to a common type and then
553multiplied together. In the latter case, sequence repetition is
554performed; a negative repetition factor yields an empty sequence.
555\index{multiplication}
556
Fred Drake5c07d9b1998-05-14 19:37:06 +0000557The \code{/} (division) operator yields the quotient of its
Fred Drakef6669171998-05-06 19:52:49 +0000558arguments. The numeric arguments are first converted to a common
559type. Plain or long integer division yields an integer of the same
560type; the result is that of mathematical division with the `floor'
561function applied to the result. Division by zero raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000562\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000563\exindex{ZeroDivisionError}
564\index{division}
565
Fred Drake5c07d9b1998-05-14 19:37:06 +0000566The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000567division of the first argument by the second. The numeric arguments
568are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000569the \exception{ZeroDivisionError} exception. The arguments may be floating
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000570point numbers, e.g. \code{3.14\%0.7} equals \code{0.34} (since
571\code{3.14} equals \code{4*0.7 + 0.34}.) The modulo operator always
572yields a result with the same sign as its second operand (or zero);
573the absolute value of the result is strictly smaller than the second
574operand.
Fred Drakef6669171998-05-06 19:52:49 +0000575\index{modulo}
576
577The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000578following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
579modulo are also connected with the built-in function \function{divmod()}:
580\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000581floating point and complex numbers; there a similar identity holds where
582\code{x/y} is replaced by \code{floor(x/y)}) or
583\code{floor((x/y).real)}, respectively.
Fred Drakef6669171998-05-06 19:52:49 +0000584
Fred Drake5c07d9b1998-05-14 19:37:06 +0000585The \code{+} (addition) operator yields the sum of its arguments.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000586The arguments must either both be numbers or both sequences of the
Fred Drakef6669171998-05-06 19:52:49 +0000587same type. In the former case, the numbers are converted to a common
588type and then added together. In the latter case, the sequences are
589concatenated.
590\index{addition}
591
Fred Drake5c07d9b1998-05-14 19:37:06 +0000592The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000593arguments. The numeric arguments are first converted to a common
594type.
595\index{subtraction}
596
597\section{Shifting operations}
598\indexii{shifting}{operation}
599
600The shifting operations have lower priority than the arithmetic
601operations:
602
603\begin{verbatim}
604shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
605\end{verbatim}
606
607These operators accept plain or long integers as arguments. The
608arguments are converted to a common type. They shift the first
609argument to the left or right by the number of bits given by the
610second argument.
611
612A right shift by \var{n} bits is defined as division by
613\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
614multiplication with \code{pow(2,\var{n})}; for plain integers there is
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000615no overflow check so in that case the operation drops bits and flips
616the sign if the result is not less than \code{pow(2,31)} in absolute
617value. Negative shift counts raise a \exception{ValueError}
618exception.
Fred Drakef6669171998-05-06 19:52:49 +0000619\exindex{ValueError}
620
621\section{Binary bit-wise operations}
622\indexiii{binary}{bit-wise}{operation}
623
624Each of the three bitwise operations has a different priority level:
625
626\begin{verbatim}
627and_expr: shift_expr | and_expr "&" shift_expr
628xor_expr: and_expr | xor_expr "^" and_expr
629or_expr: xor_expr | or_expr "|" xor_expr
630\end{verbatim}
631
Fred Drake5c07d9b1998-05-14 19:37:06 +0000632The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000633must be plain or long integers. The arguments are converted to a
634common type.
635\indexii{bit-wise}{and}
636
Fred Drake5c07d9b1998-05-14 19:37:06 +0000637The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000638arguments, which must be plain or long integers. The arguments are
639converted to a common type.
640\indexii{bit-wise}{xor}
641\indexii{exclusive}{or}
642
Fred Drake5c07d9b1998-05-14 19:37:06 +0000643The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000644arguments, which must be plain or long integers. The arguments are
645converted to a common type.
646\indexii{bit-wise}{or}
647\indexii{inclusive}{or}
648
649\section{Comparisons}
650\index{comparison}
651
Fred Drake5c07d9b1998-05-14 19:37:06 +0000652Contrary to \C, all comparison operations in Python have the same
Fred Drakef6669171998-05-06 19:52:49 +0000653priority, which is lower than that of any arithmetic, shifting or
Fred Drake5c07d9b1998-05-14 19:37:06 +0000654bitwise operation. Also contrary to \C, expressions like
655\code{a < b < c} have the interpretation that is conventional in
Fred Drakef6669171998-05-06 19:52:49 +0000656mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000657\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000658
659\begin{verbatim}
660comparison: or_expr (comp_operator or_expr)*
661comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
662\end{verbatim}
663
Fred Drake5c07d9b1998-05-14 19:37:06 +0000664Comparisons yield integer values: \code{1} for true, \code{0} for false.
Fred Drakef6669171998-05-06 19:52:49 +0000665
666Comparisons can be chained arbitrarily, e.g. \code{x < y <= z} is
667equivalent to \code{x < y and y <= z}, except that \code{y} is
668evaluated only once (but in both cases \code{z} is not evaluated at all
669when \code{x < y} is found to be false).
670\indexii{chaining}{comparisons}
671
672Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
673expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
674operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000675to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots
Fred Drakef6669171998-05-06 19:52:49 +0000676\var{y opy z}, except that each expression is evaluated at most once.
677
678Note that \var{a opa b opb c} doesn't imply any kind of comparison
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000679between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is
Fred Drakef6669171998-05-06 19:52:49 +0000680perfectly legal (though perhaps not pretty).
681
Fred Drake5c07d9b1998-05-14 19:37:06 +0000682The forms \code{<>} and \code{!=} are equivalent; for consistency with
683C, \code{!=} is preferred; where \code{!=} is mentioned below
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000684\code{<>} is also acceptable. At some point in the (far) future,
685\code{<>} may become obsolete.
Fred Drakef6669171998-05-06 19:52:49 +0000686
687The operators {\tt "<", ">", "==", ">=", "<="}, and {\tt "!="} compare
688the values of two objects. The objects needn't have the same type.
689If both are numbers, they are coverted to a common type. Otherwise,
690objects of different types {\em always} compare unequal, and are
691ordered consistently but arbitrarily.
692
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000693(This unusual definition of comparison was used to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000694definition of operations like sorting and the \keyword{in} and
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000695\keyword{not in} operators. In the future, the comparison rules for
696objects of different types are likely to change.)
Fred Drakef6669171998-05-06 19:52:49 +0000697
698Comparison of objects of the same type depends on the type:
699
700\begin{itemize}
701
702\item
703Numbers are compared arithmetically.
704
705\item
706Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +0000707(the result of the built-in function \function{ord()}) of their
708characters.
Fred Drakef6669171998-05-06 19:52:49 +0000709
710\item
711Tuples and lists are compared lexicographically using comparison of
712corresponding items.
713
714\item
715Mappings (dictionaries) are compared through lexicographic
716comparison of their sorted (key, value) lists.%
717\footnote{This is expensive since it requires sorting the keys first,
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000718but it is about the only sensible definition. An earlier version of
719Python compared dictionaries by identity only, but this caused
720surprises because people expected to be able to test a dictionary for
721emptiness by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +0000722
723\item
724Most other types compare unequal unless they are the same object;
725the choice whether one object is considered smaller or larger than
726another one is made arbitrarily but consistently within one
727execution of a program.
728
729\end{itemize}
730
Fred Drake5c07d9b1998-05-14 19:37:06 +0000731The operators \keyword{in} and \keyword{not in} test for sequence
Fred Drakef6669171998-05-06 19:52:49 +0000732membership: if \var{y} is a sequence, \code{\var{x} in \var{y}} is
733true if and only if there exists an index \var{i} such that
734\code{\var{x} = \var{y}[\var{i}]}.
735\code{\var{x} not in \var{y}} yields the inverse truth value. The
Fred Drake5c07d9b1998-05-14 19:37:06 +0000736exception \exception{TypeError} is raised when \var{y} is not a sequence,
Fred Drakef6669171998-05-06 19:52:49 +0000737or when \var{y} is a string and \var{x} is not a string of length one.%
738\footnote{The latter restriction is sometimes a nuisance.}
739\opindex{in}
740\opindex{not in}
741\indexii{membership}{test}
742\obindex{sequence}
743
Fred Drake5c07d9b1998-05-14 19:37:06 +0000744The operators \keyword{is} and \keyword{is not} test for object identity:
745\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
746are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +0000747truth value.
748\opindex{is}
749\opindex{is not}
750\indexii{identity}{test}
751
752\section{Boolean operations} \label{Booleans}
753\indexii{Boolean}{operation}
754
755Boolean operations have the lowest priority of all Python operations:
756
757\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000758expression: or_test | lambda_form
Fred Drakef6669171998-05-06 19:52:49 +0000759or_test: and_test | or_test "or" and_test
760and_test: not_test | and_test "and" not_test
761not_test: comparison | "not" not_test
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000762lambda_form: "lambda" [parameter_list]: expression
Fred Drakef6669171998-05-06 19:52:49 +0000763\end{verbatim}
764
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000765In the context of Boolean operations, and also when expressions are
Fred Drakef6669171998-05-06 19:52:49 +0000766used by control flow statements, the following values are interpreted
Fred Drake5c07d9b1998-05-14 19:37:06 +0000767as false: \code{None}, numeric zero of all types, empty sequences
Fred Drakef6669171998-05-06 19:52:49 +0000768(strings, tuples and lists), and empty mappings (dictionaries). All
769other values are interpreted as true.
770
Fred Drake5c07d9b1998-05-14 19:37:06 +0000771The operator \keyword{not} yields \code{1} if its argument is false,
772\code{0} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +0000773\opindex{not}
774
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000775The expression \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000776\var{x} is false, its value is returned; otherwise, \var{y} is
777evaluated and the resulting value is returned.
778\opindex{and}
779
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000780The expression \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000781\var{x} is true, its value is returned; otherwise, \var{y} is
782evaluated and the resulting value is returned.
783\opindex{or}
784
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000785(Note that neither \keyword{and} nor \keyword{or} restrict the value
Fred Drake5c07d9b1998-05-14 19:37:06 +0000786and type they return to \code{0} and \code{1}, but rather return the
787last evaluated argument.
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000788This is sometimes useful, e.g., if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +0000789replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +0000790\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +0000791invent a value anyway, it does not bother to return a value of the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000792same type as its argument, so e.g. \code{not 'foo'} yields \code{0},
793not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +0000794
795Lambda forms (lambda expressions) have the same syntactic position as
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000796expressions. They are a shorthand to create anonymous functions; the
797expression \code{lambda \var{arguments}: \var{expression}}
Fred Drakef6669171998-05-06 19:52:49 +0000798yields a function object that behaves virtually identical to one
799defined with
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000800
801\begin{verbatim}
802def name(arguments):
803 return expression
804\end{verbatim}
805
806See section \ref{function} for the syntax of parameter lists. Note
807that functions created with lambda forms cannot contain statements.
Fred Drakef6669171998-05-06 19:52:49 +0000808\label{lambda}
809\indexii{lambda}{expression}
810\indexii{lambda}{form}
811\indexii{anonmymous}{function}
812
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000813\strong{Programmer's note:} a lambda form defined inside a function
814has no access to names defined in the function's namespace. This is
815because Python has only two scopes: local and global. A common
816work-around is to use default argument values to pass selected
817variables into the lambda's namespace, e.g.:
Fred Drakef6669171998-05-06 19:52:49 +0000818
819\begin{verbatim}
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000820def make_incrementor(increment):
821 return lambda x, n=increment: x+n
Fred Drakef6669171998-05-06 19:52:49 +0000822\end{verbatim}
823
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000824\section{Expression lists and expression lists}
825\indexii{expression}{list}
Fred Drakef6669171998-05-06 19:52:49 +0000826
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000827\begin{verbatim}
828expression_list: expression ("," expression)* [","]
829\end{verbatim}
Fred Drakef6669171998-05-06 19:52:49 +0000830
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000831An expression (expression) list containing at least one comma yields a
832tuple. The length of the tuple is the number of expressions in the
833list. The expressions are evaluated from left to right.
Fred Drakef6669171998-05-06 19:52:49 +0000834\obindex{tuple}
835
836The trailing comma is required only to create a single tuple (a.k.a. a
837{\em singleton}); it is optional in all other cases. A single
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000838expression (expression) without a trailing comma doesn't create a
839tuple, but rather yields the value of that expression (expression).
Fred Drakef6669171998-05-06 19:52:49 +0000840(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000841\code{()}.)
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000842\indexii{trailing}{comma}
Fred Drakef6669171998-05-06 19:52:49 +0000843
844\section{Summary}
845
846The following table summarizes the operator precedences in Python,
847from lowest precedence (least binding) to highest precedence (most
848binding). Operators in the same box have the same precedence. Unless
849the syntax is explicitly given, operators are binary. Operators in
850the same box group left to right (except for comparisons, which
851chain from left to right --- see above).
852
853\begin{center}
854\begin{tabular}{|c|c|}
855\hline
Fred Drake5c07d9b1998-05-14 19:37:06 +0000856\keyword{or} & Boolean OR \\
Fred Drakef6669171998-05-06 19:52:49 +0000857\hline
Fred Drake5c07d9b1998-05-14 19:37:06 +0000858\keyword{and} & Boolean AND \\
Fred Drakef6669171998-05-06 19:52:49 +0000859\hline
Fred Drake5c07d9b1998-05-14 19:37:06 +0000860\keyword{not} \var{x} & Boolean NOT \\
Fred Drakef6669171998-05-06 19:52:49 +0000861\hline
Fred Drake5c07d9b1998-05-14 19:37:06 +0000862\keyword{in}, \keyword{not} \keyword{in} & Membership tests \\
863\keyword{is}, \keyword{is not} & Identity tests \\
Guido van Rossumc85be6a1998-05-16 02:11:10 +0000864\code{<}, \code{<=}, \code{>}, \code{>=}, \code{<>}, \code{!=}, \code{==} &
Fred Drakef6669171998-05-06 19:52:49 +0000865 Comparisons \\
866\hline
867\code{|} & Bitwise OR \\
868\hline
869\code{\^} & Bitwise XOR \\
870\hline
871\code{\&} & Bitwise AND \\
872\hline
873\code{<<}, \code{>>} & Shifts \\
874\hline
875\code{+}, \code{-} & Addition and subtraction \\
876\hline
877\code{*}, \code{/}, \code{\%} & Multiplication, division, remainder \\
878\hline
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000879\code{**} & Power \\
880\hline
Fred Drakef6669171998-05-06 19:52:49 +0000881\code{+\var{x}}, \code{-\var{x}} & Positive, negative \\
882\code{\~\var{x}} & Bitwise not \\
883\hline
884\code{\var{x}.\var{attribute}} & Attribute reference \\
885\code{\var{x}[\var{index}]} & Subscription \\
886\code{\var{x}[\var{index}:\var{index}]} & Slicing \\
887\code{\var{f}(\var{arguments}...)} & Function call \\
888\hline
889\code{(\var{expressions}\ldots)} & Binding or tuple display \\
890\code{[\var{expressions}\ldots]} & List display \\
891\code{\{\var{key}:\var{datum}\ldots\}} & Dictionary display \\
Guido van Rossum3a0ad601998-07-23 21:57:42 +0000892\code{`\var{expressions}\ldots`} & String conversion \\
Fred Drakef6669171998-05-06 19:52:49 +0000893\hline
894\end{tabular}
895\end{center}