blob: f2965609e019a722f727bbe93364337e70a26bf7 [file] [log] [blame]
Fred Drakef6669171998-05-06 19:52:49 +00001\chapter{Expressions and conditions}
2\index{expression}
3\index{condition}
4
Fred Drake5c07d9b1998-05-14 19:37:06 +00005\strong{Note:} In this and the following chapters, extended BNF
6notation will be used to describe syntax, not lexical analysis.
Fred Drakef6669171998-05-06 19:52:49 +00007\index{BNF}
8
9This chapter explains the meaning of the elements of expressions and
10conditions. Conditions are a superset of expressions, and a condition
11may be used wherever an expression is required by enclosing it in
12parentheses. The only places where expressions are used in the syntax
13instead of conditions is in expression statements and on the
14right-hand side of assignment statements; this catches some nasty bugs
Fred Drake5c07d9b1998-05-14 19:37:06 +000015like accidentally writing \code{x == 1} instead of \code{x = 1}.
Fred Drakef6669171998-05-06 19:52:49 +000016\indexii{assignment}{statement}
17
18The comma plays several roles in Python's syntax. It is usually an
19operator with a lower precedence than all others, but occasionally
20serves other purposes as well; e.g. it separates function arguments,
21is used in list and dictionary constructors, and has special semantics
Fred Drake5c07d9b1998-05-14 19:37:06 +000022in \keyword{print} statements.
Fred Drakef6669171998-05-06 19:52:49 +000023\index{comma}
24
25When (one alternative of) a syntax rule has the form
26
27\begin{verbatim}
28name: othername
29\end{verbatim}
30
Fred Drake5c07d9b1998-05-14 19:37:06 +000031and no semantics are given, the semantics of this form of \code{name}
32are the same as for \code{othername}.
Fred Drakef6669171998-05-06 19:52:49 +000033\index{syntax}
34
35\section{Arithmetic conversions}
36\indexii{arithmetic}{conversion}
37
38When a description of an arithmetic operator below uses the phrase
39``the numeric arguments are converted to a common type'',
40this both means that if either argument is not a number, a
Fred Drake5c07d9b1998-05-14 19:37:06 +000041\exception{TypeError} exception is raised, and that otherwise
Fred Drakef6669171998-05-06 19:52:49 +000042the following conversions are applied:
43\exindex{TypeError}
44\indexii{floating point}{number}
45\indexii{long}{integer}
46\indexii{plain}{integer}
47
48\begin{itemize}
49\item first, if either argument is a floating point number,
50 the other is converted to floating point;
51\item else, if either argument is a long integer,
52 the other is converted to long integer;
53\item otherwise, both must be plain integers and no conversion
54 is necessary.
55\end{itemize}
56
57\section{Atoms}
58\index{atom}
59
60Atoms are the most basic elements of expressions. Forms enclosed in
61reverse quotes or in parentheses, brackets or braces are also
62categorized syntactically as atoms. The syntax for atoms is:
63
64\begin{verbatim}
65atom: identifier | literal | enclosure
66enclosure: parenth_form|list_display|dict_display|string_conversion
67\end{verbatim}
68
69\subsection{Identifiers (Names)}
70\index{name}
71\index{identifier}
72
73An identifier occurring as an atom is a reference to a local, global
74or built-in name binding. If a name is assigned to anywhere in a code
75block (even in unreachable code), and is not mentioned in a
Fred Drake5c07d9b1998-05-14 19:37:06 +000076\keyword{global} statement in that code block, then it refers to a local
Fred Drakef6669171998-05-06 19:52:49 +000077name throughout that code block. When it is not assigned to anywhere
78in the block, or when it is assigned to but also explicitly listed in
Fred Drake5c07d9b1998-05-14 19:37:06 +000079a \keyword{global} statement, it refers to a global name if one exists,
Fred Drakef6669171998-05-06 19:52:49 +000080else to a built-in name (and this binding may dynamically change).
81\indexii{name}{binding}
82\index{code block}
83\stindex{global}
84\indexii{built-in}{name}
85\indexii{global}{name}
86
87When the name is bound to an object, evaluation of the atom yields
88that object. When a name is not bound, an attempt to evaluate it
Fred Drake5c07d9b1998-05-14 19:37:06 +000089raises a \exception{NameError} exception.
Fred Drakef6669171998-05-06 19:52:49 +000090\exindex{NameError}
91
92\subsection{Literals}
93\index{literal}
94
95Python knows string and numeric literals:
96
97\begin{verbatim}
98literal: stringliteral | integer | longinteger | floatnumber
99\end{verbatim}
100
101Evaluation of a literal yields an object of the given type (string,
102integer, long integer, floating point number) with the given value.
103The value may be approximated in the case of floating point literals.
104See section \ref{literals} for details.
105
106All literals correspond to immutable data types, and hence the
107object's identity is less important than its value. Multiple
108evaluations of literals with the same value (either the same
109occurrence in the program text or a different occurrence) may obtain
110the same object or a different object with the same value.
111\indexiii{immutable}{data}{type}
112
113(In the original implementation, all literals in the same code block
114with the same type and value yield the same object.)
115
116\subsection{Parenthesized forms}
117\index{parenthesized form}
118
119A parenthesized form is an optional condition list enclosed in
120parentheses:
121
122\begin{verbatim}
123parenth_form: "(" [condition_list] ")"
124\end{verbatim}
125
126A parenthesized condition list yields whatever that condition list
127yields.
128
129An empty pair of parentheses yields an empty tuple object. Since
130tuples are immutable, the rules for literals apply here.
131\indexii{empty}{tuple}
132
133(Note that tuples are not formed by the parentheses, but rather by use
134of the comma operator. The exception is the empty tuple, for which
135parentheses {\em are} required --- allowing unparenthesized ``nothing''
136in expressions would cause ambiguities and allow common typos to
137pass uncaught.)
138\index{comma}
139\indexii{tuple}{display}
140
141\subsection{List displays}
142\indexii{list}{display}
143
144A list display is a possibly empty series of conditions enclosed in
145square brackets:
146
147\begin{verbatim}
148list_display: "[" [condition_list] "]"
149\end{verbatim}
150
151A list display yields a new list object.
152\obindex{list}
153
154If it has no condition list, the list object has no items. Otherwise,
155the elements of the condition list are evaluated from left to right
156and inserted in the list object in that order.
157\indexii{empty}{list}
158
159\subsection{Dictionary displays} \label{dict}
160\indexii{dictionary}{display}
161
162A dictionary display is a possibly empty series of key/datum pairs
163enclosed in curly braces:
164\index{key}
165\index{datum}
166\index{key/datum pair}
167
168\begin{verbatim}
169dict_display: "{" [key_datum_list] "}"
170key_datum_list: key_datum ("," key_datum)* [","]
171key_datum: condition ":" condition
172\end{verbatim}
173
174A dictionary display yields a new dictionary object.
175\obindex{dictionary}
176
177The key/datum pairs are evaluated from left to right to define the
178entries of the dictionary: each key object is used as a key into the
179dictionary to store the corresponding datum.
180
181Restrictions on the types of the key values are listed earlier in
182section \ref{types}.
183Clashes between duplicate keys are not detected; the last
184datum (textually rightmost in the display) stored for a given key
185value prevails.
186\exindex{TypeError}
187
188\subsection{String conversions}
189\indexii{string}{conversion}
190\indexii{reverse}{quotes}
191\indexii{backward}{quotes}
192\index{back-quotes}
193
194A string conversion is a condition list enclosed in reverse (or
195backward) quotes:
196
197\begin{verbatim}
198string_conversion: "`" condition_list "`"
199\end{verbatim}
200
201A string conversion evaluates the contained condition list and
202converts the resulting object into a string according to rules
203specific to its type.
204
Fred Drake5c07d9b1998-05-14 19:37:06 +0000205If the object is a string, a number, \code{None}, or a tuple, list or
Fred Drakef6669171998-05-06 19:52:49 +0000206dictionary containing only objects whose type is one of these, the
207resulting string is a valid Python expression which can be passed to
Fred Drake5c07d9b1998-05-14 19:37:06 +0000208the built-in function \function{eval()} to yield an expression with the
Fred Drakef6669171998-05-06 19:52:49 +0000209same value (or an approximation, if floating point numbers are
210involved).
211
212(In particular, converting a string adds quotes around it and converts
213``funny'' characters to escape sequences that are safe to print.)
214
215It is illegal to attempt to convert recursive objects (e.g. lists or
216dictionaries that contain a reference to themselves, directly or
217indirectly.)
218\obindex{recursive}
219
Fred Drake5c07d9b1998-05-14 19:37:06 +0000220The built-in function \function{repr()} performs exactly the same
Fred Drakef6669171998-05-06 19:52:49 +0000221conversion in its argument as enclosing it it reverse quotes does.
Fred Drake5c07d9b1998-05-14 19:37:06 +0000222The built-in function \function{str()} performs a similar but more
Fred Drakef6669171998-05-06 19:52:49 +0000223user-friendly conversion.
224\bifuncindex{repr}
225\bifuncindex{str}
226
227\section{Primaries} \label{primaries}
228\index{primary}
229
230Primaries represent the most tightly bound operations of the language.
231Their syntax is:
232
233\begin{verbatim}
234primary: atom | attributeref | subscription | slicing | call
235\end{verbatim}
236
237\subsection{Attribute references}
238\indexii{attribute}{reference}
239
240An attribute reference is a primary followed by a period and a name:
241
242\begin{verbatim}
243attributeref: primary "." identifier
244\end{verbatim}
245
246The primary must evaluate to an object of a type that supports
247attribute references, e.g. a module or a list. This object is then
248asked to produce the attribute whose name is the identifier. If this
Fred Drake5c07d9b1998-05-14 19:37:06 +0000249attribute is not available, the exception
250\exception{AttributeError}\exindex{AttributeError} is raised.
251Otherwise, the type and value of the object produced is determined by
252the object. Multiple evaluations of the same attribute reference may
253yield different objects.
Fred Drakef6669171998-05-06 19:52:49 +0000254\obindex{module}
255\obindex{list}
256
257\subsection{Subscriptions}
258\index{subscription}
259
260A subscription selects an item of a sequence (string, tuple or list)
261or mapping (dictionary) object:
262\obindex{sequence}
263\obindex{mapping}
264\obindex{string}
265\obindex{tuple}
266\obindex{list}
267\obindex{dictionary}
268\indexii{sequence}{item}
269
270\begin{verbatim}
271subscription: primary "[" condition "]"
272\end{verbatim}
273
274The primary must evaluate to an object of a sequence or mapping type.
275
276If it is a mapping, the condition must evaluate to an object whose
277value is one of the keys of the mapping, and the subscription selects
278the value in the mapping that corresponds to that key.
279
280If it is a sequence, the condition must evaluate to a plain integer.
281If this value is negative, the length of the sequence is added to it
Fred Drake5c07d9b1998-05-14 19:37:06 +0000282(so that, e.g. \code{x[-1]} selects the last item of \code{x}.)
Fred Drakef6669171998-05-06 19:52:49 +0000283The resulting value must be a nonnegative integer smaller than the
284number of items in the sequence, and the subscription selects the item
285whose index is that value (counting from zero).
286
287A string's items are characters. A character is not a separate data
288type but a string of exactly one character.
289\index{character}
290\indexii{string}{item}
291
292\subsection{Slicings}
293\index{slicing}
294\index{slice}
295
296A slicing (or slice) selects a range of items in a sequence (string,
297tuple or list) object:
298\obindex{sequence}
299\obindex{string}
300\obindex{tuple}
301\obindex{list}
302
303\begin{verbatim}
304slicing: primary "[" [condition] ":" [condition] "]"
305\end{verbatim}
306
307The primary must evaluate to a sequence object. The lower and upper
308bound expressions, if present, must evaluate to plain integers;
309defaults are zero and the sequence's length, respectively. If either
310bound is negative, the sequence's length is added to it. The slicing
311now selects all items with index \var{k} such that
312\code{\var{i} <= \var{k} < \var{j}} where \var{i}
313and \var{j} are the specified lower and upper bounds. This may be an
314empty sequence. It is not an error if \var{i} or \var{j} lie outside the
315range of valid indexes (such items don't exist so they aren't
316selected).
317
318\subsection{Calls} \label{calls}
319\index{call}
320
321A call calls a callable object (e.g. a function) with a possibly empty
322series of arguments:\footnote{The new syntax for keyword arguments is
323not yet documented in this manual. See chapter 12 of the Tutorial.}
324\obindex{callable}
325
326\begin{verbatim}
327call: primary "(" [condition_list] ")"
328\end{verbatim}
329
330The primary must evaluate to a callable object (user-defined
331functions, built-in functions, methods of built-in objects, class
332objects, and methods of class instances are callable). If it is a
333class, the argument list must be empty; otherwise, the arguments are
334evaluated.
335
Fred Drake5c07d9b1998-05-14 19:37:06 +0000336A call always returns some value, possibly \code{None}, unless it
Fred Drakef6669171998-05-06 19:52:49 +0000337raises an exception. How this value is computed depends on the type
338of the callable object. If it is:
339
340\begin{description}
341
342\item[a user-defined function:] the code block for the function is
343executed, passing it the argument list. The first thing the code
344block will do is bind the formal parameters to the arguments; this is
345described in section \ref{function}. When the code block executes a
Fred Drake5c07d9b1998-05-14 19:37:06 +0000346\keyword{return} statement, this specifies the return value of the
Fred Drakef6669171998-05-06 19:52:49 +0000347function call.
348\indexii{function}{call}
349\indexiii{user-defined}{function}{call}
350\obindex{user-defined function}
351\obindex{function}
352
353\item[a built-in function or method:] the result is up to the
354interpreter; see the library reference manual for the descriptions of
355built-in functions and methods.
356\indexii{function}{call}
357\indexii{built-in function}{call}
358\indexii{method}{call}
359\indexii{built-in method}{call}
360\obindex{built-in method}
361\obindex{built-in function}
362\obindex{method}
363\obindex{function}
364
365\item[a class object:] a new instance of that class is returned.
366\obindex{class}
367\indexii{class object}{call}
368
369\item[a class instance method:] the corresponding user-defined
370function is called, with an argument list that is one longer than the
371argument list of the call: the instance becomes the first argument.
372\obindex{class instance}
373\obindex{instance}
374\indexii{instance}{call}
375\indexii{class instance}{call}
376
377\end{description}
378
379\section{Unary arithmetic operations}
380\indexiii{unary}{arithmetic}{operation}
381\indexiii{unary}{bit-wise}{operation}
382
383All unary arithmetic (and bit-wise) operations have the same priority:
384
385\begin{verbatim}
386u_expr: primary | "-" u_expr | "+" u_expr | "~" u_expr
387\end{verbatim}
388
Fred Drake5c07d9b1998-05-14 19:37:06 +0000389The unary \code{-} (minus) operator yields the negation of its
Fred Drakef6669171998-05-06 19:52:49 +0000390numeric argument.
391\index{negation}
392\index{minus}
393
Fred Drake5c07d9b1998-05-14 19:37:06 +0000394The unary \code{+} (plus) operator yields its numeric argument
Fred Drakef6669171998-05-06 19:52:49 +0000395unchanged.
396\index{plus}
397
Fred Drake5c07d9b1998-05-14 19:37:06 +0000398The unary \code{~} (invert) operator yields the bit-wise inversion
Fred Drakef6669171998-05-06 19:52:49 +0000399of its plain or long integer argument. The bit-wise inversion of
Fred Drake5c07d9b1998-05-14 19:37:06 +0000400\code{x} is defined as \code{-(x+1)}.
Fred Drakef6669171998-05-06 19:52:49 +0000401\index{inversion}
402
403In all three cases, if the argument does not have the proper type,
Fred Drake5c07d9b1998-05-14 19:37:06 +0000404a \exception{TypeError} exception is raised.
Fred Drakef6669171998-05-06 19:52:49 +0000405\exindex{TypeError}
406
407\section{Binary arithmetic operations}
408\indexiii{binary}{arithmetic}{operation}
409
410The binary arithmetic operations have the conventional priority
411levels. Note that some of these operations also apply to certain
412non-numeric types. There is no ``power'' operator, so there are only
413two levels, one for multiplicative operators and one for additive
414operators:
415
416\begin{verbatim}
417m_expr: u_expr | m_expr "*" u_expr
418 | m_expr "/" u_expr | m_expr "%" u_expr
419a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
420\end{verbatim}
421
Fred Drake5c07d9b1998-05-14 19:37:06 +0000422The \code{*} (multiplication) operator yields the product of its
Fred Drakef6669171998-05-06 19:52:49 +0000423arguments. The arguments must either both be numbers, or one argument
424must be a plain integer and the other must be a sequence. In the
425former case, the numbers are converted to a common type and then
426multiplied together. In the latter case, sequence repetition is
427performed; a negative repetition factor yields an empty sequence.
428\index{multiplication}
429
Fred Drake5c07d9b1998-05-14 19:37:06 +0000430The \code{/} (division) operator yields the quotient of its
Fred Drakef6669171998-05-06 19:52:49 +0000431arguments. The numeric arguments are first converted to a common
432type. Plain or long integer division yields an integer of the same
433type; the result is that of mathematical division with the `floor'
434function applied to the result. Division by zero raises the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000435\exception{ZeroDivisionError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000436\exindex{ZeroDivisionError}
437\index{division}
438
Fred Drake5c07d9b1998-05-14 19:37:06 +0000439The \code{\%} (modulo) operator yields the remainder from the
Fred Drakef6669171998-05-06 19:52:49 +0000440division of the first argument by the second. The numeric arguments
441are first converted to a common type. A zero right argument raises
Fred Drake5c07d9b1998-05-14 19:37:06 +0000442the \exception{ZeroDivisionError} exception. The arguments may be floating
443point numbers, e.g. \code{3.14 \% 0.7} equals \code{0.34}. The modulo
Fred Drakef6669171998-05-06 19:52:49 +0000444operator always yields a result with the same sign as its second
445operand (or zero); the absolute value of the result is strictly
446smaller than the second operand.
447\index{modulo}
448
449The integer division and modulo operators are connected by the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000450following identity: \code{x == (x/y)*y + (x\%y)}. Integer division and
451modulo are also connected with the built-in function \function{divmod()}:
452\code{divmod(x, y) == (x/y, x\%y)}. These identities don't hold for
Fred Drakef6669171998-05-06 19:52:49 +0000453floating point numbers; there a similar identity holds where
Fred Drake5c07d9b1998-05-14 19:37:06 +0000454\code{x/y} is replaced by \code{floor(x/y)}).
Fred Drakef6669171998-05-06 19:52:49 +0000455
Fred Drake5c07d9b1998-05-14 19:37:06 +0000456The \code{+} (addition) operator yields the sum of its arguments.
Fred Drakef6669171998-05-06 19:52:49 +0000457The arguments must either both be numbers, or both sequences of the
458same type. In the former case, the numbers are converted to a common
459type and then added together. In the latter case, the sequences are
460concatenated.
461\index{addition}
462
Fred Drake5c07d9b1998-05-14 19:37:06 +0000463The \code{-} (subtraction) operator yields the difference of its
Fred Drakef6669171998-05-06 19:52:49 +0000464arguments. The numeric arguments are first converted to a common
465type.
466\index{subtraction}
467
468\section{Shifting operations}
469\indexii{shifting}{operation}
470
471The shifting operations have lower priority than the arithmetic
472operations:
473
474\begin{verbatim}
475shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
476\end{verbatim}
477
478These operators accept plain or long integers as arguments. The
479arguments are converted to a common type. They shift the first
480argument to the left or right by the number of bits given by the
481second argument.
482
483A right shift by \var{n} bits is defined as division by
484\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
485multiplication with \code{pow(2,\var{n})}; for plain integers there is
486no overflow check so this drops bits and flips the sign if the result
487is not less than \code{pow(2,31)} in absolute value.
488
Fred Drake5c07d9b1998-05-14 19:37:06 +0000489Negative shift counts raise a \exception{ValueError} exception.
Fred Drakef6669171998-05-06 19:52:49 +0000490\exindex{ValueError}
491
492\section{Binary bit-wise operations}
493\indexiii{binary}{bit-wise}{operation}
494
495Each of the three bitwise operations has a different priority level:
496
497\begin{verbatim}
498and_expr: shift_expr | and_expr "&" shift_expr
499xor_expr: and_expr | xor_expr "^" and_expr
500or_expr: xor_expr | or_expr "|" xor_expr
501\end{verbatim}
502
Fred Drake5c07d9b1998-05-14 19:37:06 +0000503The \code{\&} operator yields the bitwise AND of its arguments, which
Fred Drakef6669171998-05-06 19:52:49 +0000504must be plain or long integers. The arguments are converted to a
505common type.
506\indexii{bit-wise}{and}
507
Fred Drake5c07d9b1998-05-14 19:37:06 +0000508The \code{\^} operator yields the bitwise XOR (exclusive OR) of its
Fred Drakef6669171998-05-06 19:52:49 +0000509arguments, which must be plain or long integers. The arguments are
510converted to a common type.
511\indexii{bit-wise}{xor}
512\indexii{exclusive}{or}
513
Fred Drake5c07d9b1998-05-14 19:37:06 +0000514The \code{|} operator yields the bitwise (inclusive) OR of its
Fred Drakef6669171998-05-06 19:52:49 +0000515arguments, which must be plain or long integers. The arguments are
516converted to a common type.
517\indexii{bit-wise}{or}
518\indexii{inclusive}{or}
519
520\section{Comparisons}
521\index{comparison}
522
Fred Drake5c07d9b1998-05-14 19:37:06 +0000523Contrary to \C, all comparison operations in Python have the same
Fred Drakef6669171998-05-06 19:52:49 +0000524priority, which is lower than that of any arithmetic, shifting or
Fred Drake5c07d9b1998-05-14 19:37:06 +0000525bitwise operation. Also contrary to \C, expressions like
526\code{a < b < c} have the interpretation that is conventional in
Fred Drakef6669171998-05-06 19:52:49 +0000527mathematics:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000528\indexii{C}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000529
530\begin{verbatim}
531comparison: or_expr (comp_operator or_expr)*
532comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
533\end{verbatim}
534
Fred Drake5c07d9b1998-05-14 19:37:06 +0000535Comparisons yield integer values: \code{1} for true, \code{0} for false.
Fred Drakef6669171998-05-06 19:52:49 +0000536
537Comparisons can be chained arbitrarily, e.g. \code{x < y <= z} is
538equivalent to \code{x < y and y <= z}, except that \code{y} is
539evaluated only once (but in both cases \code{z} is not evaluated at all
540when \code{x < y} is found to be false).
541\indexii{chaining}{comparisons}
542
543Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
544expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
545operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
Fred Drake5c07d9b1998-05-14 19:37:06 +0000546to \var{a opa b} \keyword{and} \var{b opb c} \keyword{and} \ldots \keyword{and}
Fred Drakef6669171998-05-06 19:52:49 +0000547\var{y opy z}, except that each expression is evaluated at most once.
548
549Note that \var{a opa b opb c} doesn't imply any kind of comparison
550between \var{a} and \var{c}, so that e.g.\ \code{x < y > z} is
551perfectly legal (though perhaps not pretty).
552
Fred Drake5c07d9b1998-05-14 19:37:06 +0000553The forms \code{<>} and \code{!=} are equivalent; for consistency with
554C, \code{!=} is preferred; where \code{!=} is mentioned below
555\code{<>} is also implied.
Fred Drakef6669171998-05-06 19:52:49 +0000556
557The operators {\tt "<", ">", "==", ">=", "<="}, and {\tt "!="} compare
558the values of two objects. The objects needn't have the same type.
559If both are numbers, they are coverted to a common type. Otherwise,
560objects of different types {\em always} compare unequal, and are
561ordered consistently but arbitrarily.
562
563(This unusual definition of comparison is done to simplify the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000564definition of operations like sorting and the \keyword{in} and
565\keyword{not in} operators.)
Fred Drakef6669171998-05-06 19:52:49 +0000566
567Comparison of objects of the same type depends on the type:
568
569\begin{itemize}
570
571\item
572Numbers are compared arithmetically.
573
574\item
575Strings are compared lexicographically using the numeric equivalents
Fred Drake5c07d9b1998-05-14 19:37:06 +0000576(the result of the built-in function \function{ord()}) of their
577characters.
Fred Drakef6669171998-05-06 19:52:49 +0000578
579\item
580Tuples and lists are compared lexicographically using comparison of
581corresponding items.
582
583\item
584Mappings (dictionaries) are compared through lexicographic
585comparison of their sorted (key, value) lists.%
586\footnote{This is expensive since it requires sorting the keys first,
587but about the only sensible definition. An earlier version of Python
588compared dictionaries by identity only, but this caused surprises
589because people expected to be able to test a dictionary for emptiness
Fred Drake5c07d9b1998-05-14 19:37:06 +0000590by comparing it to \code{\{\}}.}
Fred Drakef6669171998-05-06 19:52:49 +0000591
592\item
593Most other types compare unequal unless they are the same object;
594the choice whether one object is considered smaller or larger than
595another one is made arbitrarily but consistently within one
596execution of a program.
597
598\end{itemize}
599
Fred Drake5c07d9b1998-05-14 19:37:06 +0000600The operators \keyword{in} and \keyword{not in} test for sequence
Fred Drakef6669171998-05-06 19:52:49 +0000601membership: if \var{y} is a sequence, \code{\var{x} in \var{y}} is
602true if and only if there exists an index \var{i} such that
603\code{\var{x} = \var{y}[\var{i}]}.
604\code{\var{x} not in \var{y}} yields the inverse truth value. The
Fred Drake5c07d9b1998-05-14 19:37:06 +0000605exception \exception{TypeError} is raised when \var{y} is not a sequence,
Fred Drakef6669171998-05-06 19:52:49 +0000606or when \var{y} is a string and \var{x} is not a string of length one.%
607\footnote{The latter restriction is sometimes a nuisance.}
608\opindex{in}
609\opindex{not in}
610\indexii{membership}{test}
611\obindex{sequence}
612
Fred Drake5c07d9b1998-05-14 19:37:06 +0000613The operators \keyword{is} and \keyword{is not} test for object identity:
614\code{\var{x} is \var{y}} is true if and only if \var{x} and \var{y}
615are the same object. \code{\var{x} is not \var{y}} yields the inverse
Fred Drakef6669171998-05-06 19:52:49 +0000616truth value.
617\opindex{is}
618\opindex{is not}
619\indexii{identity}{test}
620
621\section{Boolean operations} \label{Booleans}
622\indexii{Boolean}{operation}
623
624Boolean operations have the lowest priority of all Python operations:
625
626\begin{verbatim}
627condition: or_test | lambda_form
628or_test: and_test | or_test "or" and_test
629and_test: not_test | and_test "and" not_test
630not_test: comparison | "not" not_test
631lambda_form: "lambda" [parameter_list]: condition
632\end{verbatim}
633
634In the context of Boolean operations, and also when conditions are
635used by control flow statements, the following values are interpreted
Fred Drake5c07d9b1998-05-14 19:37:06 +0000636as false: \code{None}, numeric zero of all types, empty sequences
Fred Drakef6669171998-05-06 19:52:49 +0000637(strings, tuples and lists), and empty mappings (dictionaries). All
638other values are interpreted as true.
639
Fred Drake5c07d9b1998-05-14 19:37:06 +0000640The operator \keyword{not} yields \code{1} if its argument is false,
641\code{0} otherwise.
Fred Drakef6669171998-05-06 19:52:49 +0000642\opindex{not}
643
Fred Drake5c07d9b1998-05-14 19:37:06 +0000644The condition \code{\var{x} and \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000645\var{x} is false, its value is returned; otherwise, \var{y} is
646evaluated and the resulting value is returned.
647\opindex{and}
648
Fred Drake5c07d9b1998-05-14 19:37:06 +0000649The condition \code{\var{x} or \var{y}} first evaluates \var{x}; if
Fred Drakef6669171998-05-06 19:52:49 +0000650\var{x} is true, its value is returned; otherwise, \var{y} is
651evaluated and the resulting value is returned.
652\opindex{or}
653
Fred Drake5c07d9b1998-05-14 19:37:06 +0000654(Note that \keyword{and} and \keyword{or} do not restrict the value
655and type they return to \code{0} and \code{1}, but rather return the
656last evaluated argument.
657This is sometimes useful, e.g.\ if \code{s} is a string that should be
Fred Drakef6669171998-05-06 19:52:49 +0000658replaced by a default value if it is empty, the expression
Fred Drake5c07d9b1998-05-14 19:37:06 +0000659\code{s or 'foo'} yields the desired value. Because \keyword{not} has to
Fred Drakef6669171998-05-06 19:52:49 +0000660invent a value anyway, it does not bother to return a value of the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000661same type as its argument, so e.g. \code{not 'foo'} yields \code{0},
662not \code{''}.)
Fred Drakef6669171998-05-06 19:52:49 +0000663
664Lambda forms (lambda expressions) have the same syntactic position as
665conditions. They are a shorthand to create anonymous functions; the
Fred Drake5c07d9b1998-05-14 19:37:06 +0000666expression \code{lambda \var{arguments}: \var{condition}}
Fred Drakef6669171998-05-06 19:52:49 +0000667yields a function object that behaves virtually identical to one
668defined with
Fred Drake5c07d9b1998-05-14 19:37:06 +0000669\code{def \var{name}(\var{arguments}): return \var{condition}}.
Fred Drakef6669171998-05-06 19:52:49 +0000670See section \ref{function} for the syntax of
671parameter lists. Note that functions created with lambda forms cannot
672contain statements.
673\label{lambda}
674\indexii{lambda}{expression}
675\indexii{lambda}{form}
676\indexii{anonmymous}{function}
677
678\section{Expression lists and condition lists}
679\indexii{expression}{list}
680\indexii{condition}{list}
681
682\begin{verbatim}
683expression_list: or_expr ("," or_expr)* [","]
684condintion_list: condition ("," condition)* [","]
685\end{verbatim}
686
687The only difference between expression lists and condition lists is
688the lowest priority of operators that can be used in them without
689being enclosed in parentheses; condition lists allow all operators,
690while expression lists don't allow comparisons and Boolean operators
691(they do allow bitwise and shift operators though).
692
693Expression lists are used in expression statements and assignments;
694condition lists are used everywhere else where a list of
695comma-separated values is required.
696
697An expression (condition) list containing at least one comma yields a
698tuple. The length of the tuple is the number of expressions
699(conditions) in the list. The expressions (conditions) are evaluated
700from left to right. (Condition lists are used syntactically is a few
701places where no tuple is constructed but a list of values is needed
702nevertheless.)
703\obindex{tuple}
704
705The trailing comma is required only to create a single tuple (a.k.a. a
706{\em singleton}); it is optional in all other cases. A single
707expression (condition) without a trailing comma doesn't create a
708tuple, but rather yields the value of that expression (condition).
709\indexii{trailing}{comma}
710
711(To create an empty tuple, use an empty pair of parentheses:
Fred Drake5c07d9b1998-05-14 19:37:06 +0000712\code{()}.)
Fred Drakef6669171998-05-06 19:52:49 +0000713
714\section{Summary}
715
716The following table summarizes the operator precedences in Python,
717from lowest precedence (least binding) to highest precedence (most
718binding). Operators in the same box have the same precedence. Unless
719the syntax is explicitly given, operators are binary. Operators in
720the same box group left to right (except for comparisons, which
721chain from left to right --- see above).
722
723\begin{center}
724\begin{tabular}{|c|c|}
725\hline
Fred Drake5c07d9b1998-05-14 19:37:06 +0000726\keyword{or} & Boolean OR \\
Fred Drakef6669171998-05-06 19:52:49 +0000727\hline
Fred Drake5c07d9b1998-05-14 19:37:06 +0000728\keyword{and} & Boolean AND \\
Fred Drakef6669171998-05-06 19:52:49 +0000729\hline
Fred Drake5c07d9b1998-05-14 19:37:06 +0000730\keyword{not} \var{x} & Boolean NOT \\
Fred Drakef6669171998-05-06 19:52:49 +0000731\hline
Fred Drake5c07d9b1998-05-14 19:37:06 +0000732\keyword{in}, \keyword{not} \keyword{in} & Membership tests \\
733\keyword{is}, \keyword{is not} & Identity tests \\
Fred Drakef6669171998-05-06 19:52:49 +0000734\code{<}, \code{<=}, \code{>}, \code{>=}, \code{<>}, \code{!=}, \code{=} &
735 Comparisons \\
736\hline
737\code{|} & Bitwise OR \\
738\hline
739\code{\^} & Bitwise XOR \\
740\hline
741\code{\&} & Bitwise AND \\
742\hline
743\code{<<}, \code{>>} & Shifts \\
744\hline
745\code{+}, \code{-} & Addition and subtraction \\
746\hline
747\code{*}, \code{/}, \code{\%} & Multiplication, division, remainder \\
748\hline
749\code{+\var{x}}, \code{-\var{x}} & Positive, negative \\
750\code{\~\var{x}} & Bitwise not \\
751\hline
752\code{\var{x}.\var{attribute}} & Attribute reference \\
753\code{\var{x}[\var{index}]} & Subscription \\
754\code{\var{x}[\var{index}:\var{index}]} & Slicing \\
755\code{\var{f}(\var{arguments}...)} & Function call \\
756\hline
757\code{(\var{expressions}\ldots)} & Binding or tuple display \\
758\code{[\var{expressions}\ldots]} & List display \\
759\code{\{\var{key}:\var{datum}\ldots\}} & Dictionary display \\
760\code{`\var{expression}\ldots`} & String conversion \\
761\hline
762\end{tabular}
763\end{center}