blob: 3db25280d6e815d656c2ceaa501fda7c80a00753 [file] [log] [blame]
Guido van Rossum46f3e001992-08-14 09:11:01 +00001\chapter{Expressions and conditions}
2\index{expression}
3\index{condition}
4
5{\bf Note:} In this and the following chapters, extended BNF notation
6will be used to describe syntax, not lexical analysis.
7\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
Guido van Rossum6938f061994-08-01 12:22:53 +000015like accidentally writing \verb@x == 1@ instead of \verb@x = 1@.
Guido van Rossum46f3e001992-08-14 09:11:01 +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
Guido van Rossum6938f061994-08-01 12:22:53 +000022in \verb@print@ statements.
Guido van Rossum46f3e001992-08-14 09:11:01 +000023\index{comma}
24
25When (one alternative of) a syntax rule has the form
26
27\begin{verbatim}
28name: othername
29\end{verbatim}
30
Guido van Rossum6938f061994-08-01 12:22:53 +000031and no semantics are given, the semantics of this form of \verb@name@
32are the same as for \verb@othername@.
Guido van Rossum46f3e001992-08-14 09:11:01 +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
Guido van Rossum6938f061994-08-01 12:22:53 +000041\verb@TypeError@ exception is raised, and that otherwise
Guido van Rossum46f3e001992-08-14 09:11:01 +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
Guido van Rossum6938f061994-08-01 12:22:53 +000074or 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
76\verb@global@ statement in that code block, then it refers to a local
77name 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
79a \verb@global@ statement, it refers to a global name if one exists,
80else to a built-in name (and this binding may dynamically change).
Guido van Rossum46f3e001992-08-14 09:11:01 +000081\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
Guido van Rossum6938f061994-08-01 12:22:53 +000089raises a \verb@NameError@ exception.
Guido van Rossum46f3e001992-08-14 09:11:01 +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''
Guido van Rossum16d6e711994-08-08 12:30:22 +0000136in expressions would cause ambiguities and allow common typos to
Guido van Rossum46f3e001992-08-14 09:11:01 +0000137pass 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
Guido van Rossumb2c65561993-05-12 08:53:36 +0000181Restrictions on the types of the key values are listed earlier in
182section \ref{types}.
183Clashes between duplicate keys are not detected; the last
Guido van Rossum46f3e001992-08-14 09:11:01 +0000184datum (textually rightmost in the display) stored for a given key
185value prevails.
186\exindex{TypeError}
187
188\subsection{String conversions}
189\indexii{string}{conversion}
Guido van Rossum31cce971995-01-04 19:17:34 +0000190\indexii{reverse}{quotes}
191\indexii{backward}{quotes}
192\index{back-quotes}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000193
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
Guido van Rossum6938f061994-08-01 12:22:53 +0000205If the object is a string, a number, \verb@None@, or a tuple, list or
Guido van Rossum46f3e001992-08-14 09:11:01 +0000206dictionary containing only objects whose type is one of these, the
207resulting string is a valid Python expression which can be passed to
Guido van Rossum6938f061994-08-01 12:22:53 +0000208the built-in function \verb@eval()@ to yield an expression with the
Guido van Rossum46f3e001992-08-14 09:11:01 +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
Guido van Rossum31cce971995-01-04 19:17:34 +0000220The built-in function \verb@repr()@ performs exactly the same
221conversion in its argument as enclosing it it reverse quotes does.
222The built-in function \verb@str()@ performs a similar but more
223user-friendly conversion.
224\bifuncindex{repr}
225\bifuncindex{str}
226
Guido van Rossum46f3e001992-08-14 09:11:01 +0000227\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
Guido van Rossum6938f061994-08-01 12:22:53 +0000249attribute is not available, the exception \verb@AttributeError@ is
Guido van Rossum46f3e001992-08-14 09:11:01 +0000250raised. Otherwise, the type and value of the object produced is
251determined by the object. Multiple evaluations of the same attribute
252reference may yield different objects.
253\obindex{module}
254\obindex{list}
255
256\subsection{Subscriptions}
257\index{subscription}
258
259A subscription selects an item of a sequence (string, tuple or list)
260or mapping (dictionary) object:
261\obindex{sequence}
262\obindex{mapping}
263\obindex{string}
264\obindex{tuple}
265\obindex{list}
266\obindex{dictionary}
267\indexii{sequence}{item}
268
269\begin{verbatim}
270subscription: primary "[" condition "]"
271\end{verbatim}
272
273The primary must evaluate to an object of a sequence or mapping type.
274
275If it is a mapping, the condition must evaluate to an object whose
276value is one of the keys of the mapping, and the subscription selects
277the value in the mapping that corresponds to that key.
278
279If it is a sequence, the condition must evaluate to a plain integer.
280If this value is negative, the length of the sequence is added to it
Guido van Rossum6938f061994-08-01 12:22:53 +0000281(so that, e.g. \verb@x[-1]@ selects the last item of \verb@x@.)
Guido van Rossum46f3e001992-08-14 09:11:01 +0000282The resulting value must be a nonnegative integer smaller than the
283number of items in the sequence, and the subscription selects the item
284whose index is that value (counting from zero).
285
286A string's items are characters. A character is not a separate data
287type but a string of exactly one character.
288\index{character}
289\indexii{string}{item}
290
291\subsection{Slicings}
292\index{slicing}
293\index{slice}
294
295A slicing (or slice) selects a range of items in a sequence (string,
296tuple or list) object:
297\obindex{sequence}
298\obindex{string}
299\obindex{tuple}
300\obindex{list}
301
302\begin{verbatim}
303slicing: primary "[" [condition] ":" [condition] "]"
304\end{verbatim}
305
306The primary must evaluate to a sequence object. The lower and upper
307bound expressions, if present, must evaluate to plain integers;
308defaults are zero and the sequence's length, respectively. If either
309bound is negative, the sequence's length is added to it. The slicing
Guido van Rossuma5475471995-03-16 14:44:07 +0000310now selects all items with index \var{k} such that
311\code{\var{i} <= \var{k} < \var{j}} where \var{i}
312and \var{j} are the specified lower and upper bounds. This may be an
313empty sequence. It is not an error if \var{i} or \var{j} lie outside the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000314range of valid indexes (such items don't exist so they aren't
315selected).
316
317\subsection{Calls} \label{calls}
318\index{call}
319
320A call calls a callable object (e.g. a function) with a possibly empty
321series of arguments:
322\obindex{callable}
323
324\begin{verbatim}
325call: primary "(" [condition_list] ")"
326\end{verbatim}
327
328The primary must evaluate to a callable object (user-defined
329functions, built-in functions, methods of built-in objects, class
330objects, and methods of class instances are callable). If it is a
331class, the argument list must be empty; otherwise, the arguments are
332evaluated.
333
Guido van Rossum6938f061994-08-01 12:22:53 +0000334A call always returns some value, possibly \verb@None@, unless it
Guido van Rossum46f3e001992-08-14 09:11:01 +0000335raises an exception. How this value is computed depends on the type
336of the callable object. If it is:
337
338\begin{description}
339
340\item[a user-defined function:] the code block for the function is
341executed, passing it the argument list. The first thing the code
342block will do is bind the formal parameters to the arguments; this is
343described in section \ref{function}. When the code block executes a
Guido van Rossum6938f061994-08-01 12:22:53 +0000344\verb@return@ statement, this specifies the return value of the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000345function call.
346\indexii{function}{call}
347\indexiii{user-defined}{function}{call}
348\obindex{user-defined function}
349\obindex{function}
350
351\item[a built-in function or method:] the result is up to the
352interpreter; see the library reference manual for the descriptions of
353built-in functions and methods.
354\indexii{function}{call}
355\indexii{built-in function}{call}
356\indexii{method}{call}
357\indexii{built-in method}{call}
358\obindex{built-in method}
359\obindex{built-in function}
360\obindex{method}
361\obindex{function}
362
363\item[a class object:] a new instance of that class is returned.
364\obindex{class}
365\indexii{class object}{call}
366
367\item[a class instance method:] the corresponding user-defined
368function is called, with an argument list that is one longer than the
369argument list of the call: the instance becomes the first argument.
370\obindex{class instance}
371\obindex{instance}
372\indexii{instance}{call}
373\indexii{class instance}{call}
374
375\end{description}
376
377\section{Unary arithmetic operations}
378\indexiii{unary}{arithmetic}{operation}
379\indexiii{unary}{bit-wise}{operation}
380
381All unary arithmetic (and bit-wise) operations have the same priority:
382
383\begin{verbatim}
384u_expr: primary | "-" u_expr | "+" u_expr | "~" u_expr
385\end{verbatim}
386
Guido van Rossum6938f061994-08-01 12:22:53 +0000387The unary \verb@"-"@ (minus) operator yields the negation of its
Guido van Rossum46f3e001992-08-14 09:11:01 +0000388numeric argument.
389\index{negation}
390\index{minus}
391
Guido van Rossum6938f061994-08-01 12:22:53 +0000392The unary \verb@"+"@ (plus) operator yields its numeric argument
Guido van Rossum46f3e001992-08-14 09:11:01 +0000393unchanged.
394\index{plus}
395
Guido van Rossum6938f061994-08-01 12:22:53 +0000396The unary \verb@"~"@ (invert) operator yields the bit-wise inversion
Guido van Rossum46f3e001992-08-14 09:11:01 +0000397of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum6938f061994-08-01 12:22:53 +0000398\verb@x@ is defined as \verb@-(x+1)@.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000399\index{inversion}
400
401In all three cases, if the argument does not have the proper type,
Guido van Rossum6938f061994-08-01 12:22:53 +0000402a \verb@TypeError@ exception is raised.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000403\exindex{TypeError}
404
405\section{Binary arithmetic operations}
406\indexiii{binary}{arithmetic}{operation}
407
408The binary arithmetic operations have the conventional priority
409levels. Note that some of these operations also apply to certain
410non-numeric types. There is no ``power'' operator, so there are only
411two levels, one for multiplicative operators and one for additive
412operators:
413
414\begin{verbatim}
415m_expr: u_expr | m_expr "*" u_expr
416 | m_expr "/" u_expr | m_expr "%" u_expr
417a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
418\end{verbatim}
419
Guido van Rossum6938f061994-08-01 12:22:53 +0000420The \verb@"*"@ (multiplication) operator yields the product of its
Guido van Rossum46f3e001992-08-14 09:11:01 +0000421arguments. The arguments must either both be numbers, or one argument
422must be a plain integer and the other must be a sequence. In the
423former case, the numbers are converted to a common type and then
424multiplied together. In the latter case, sequence repetition is
425performed; a negative repetition factor yields an empty sequence.
426\index{multiplication}
427
Guido van Rossum6938f061994-08-01 12:22:53 +0000428The \verb@"/"@ (division) operator yields the quotient of its
Guido van Rossum46f3e001992-08-14 09:11:01 +0000429arguments. The numeric arguments are first converted to a common
430type. Plain or long integer division yields an integer of the same
431type; the result is that of mathematical division with the `floor'
432function applied to the result. Division by zero raises the
Guido van Rossum6938f061994-08-01 12:22:53 +0000433\verb@ZeroDivisionError@ exception.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000434\exindex{ZeroDivisionError}
435\index{division}
436
Guido van Rossum6938f061994-08-01 12:22:53 +0000437The \verb@"%"@ (modulo) operator yields the remainder from the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000438division of the first argument by the second. The numeric arguments
439are first converted to a common type. A zero right argument raises
Guido van Rossum6938f061994-08-01 12:22:53 +0000440the \verb@ZeroDivisionError@ exception. The arguments may be floating
441point numbers, e.g. \verb@3.14 % 0.7@ equals \verb@0.34@. The modulo
Guido van Rossum46f3e001992-08-14 09:11:01 +0000442operator always yields a result with the same sign as its second
443operand (or zero); the absolute value of the result is strictly
444smaller than the second operand.
445\index{modulo}
446
447The integer division and modulo operators are connected by the
Guido van Rossum6938f061994-08-01 12:22:53 +0000448following identity: \verb@x == (x/y)*y + (x%y)@. Integer division and
449modulo are also connected with the built-in function \verb@divmod()@:
450\verb@divmod(x, y) == (x/y, x%y)@. These identities don't hold for
Guido van Rossum46f3e001992-08-14 09:11:01 +0000451floating point numbers; there a similar identity holds where
Guido van Rossum6938f061994-08-01 12:22:53 +0000452\verb@x/y@ is replaced by \verb@floor(x/y)@).
Guido van Rossum46f3e001992-08-14 09:11:01 +0000453
Guido van Rossum6938f061994-08-01 12:22:53 +0000454The \verb@"+"@ (addition) operator yields the sum of its arguments.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000455The arguments must either both be numbers, or both sequences of the
456same type. In the former case, the numbers are converted to a common
457type and then added together. In the latter case, the sequences are
458concatenated.
459\index{addition}
460
Guido van Rossum6938f061994-08-01 12:22:53 +0000461The \verb@"-"@ (subtraction) operator yields the difference of its
Guido van Rossum46f3e001992-08-14 09:11:01 +0000462arguments. The numeric arguments are first converted to a common
463type.
464\index{subtraction}
465
466\section{Shifting operations}
467\indexii{shifting}{operation}
468
469The shifting operations have lower priority than the arithmetic
470operations:
471
472\begin{verbatim}
473shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
474\end{verbatim}
475
476These operators accept plain or long integers as arguments. The
477arguments are converted to a common type. They shift the first
478argument to the left or right by the number of bits given by the
479second argument.
480
Guido van Rossuma5475471995-03-16 14:44:07 +0000481A right shift by \var{n} bits is defined as division by
482\code{pow(2,\var{n})}. A left shift by \var{n} bits is defined as
483multiplication with \code{pow(2,\var{n})}; for plain integers there is
484no overflow check so this drops bits and flips the sign if the result
485is not less than \code{pow(2,31)} in absolute value.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000486
Guido van Rossum6938f061994-08-01 12:22:53 +0000487Negative shift counts raise a \verb@ValueError@ exception.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000488\exindex{ValueError}
489
490\section{Binary bit-wise operations}
491\indexiii{binary}{bit-wise}{operation}
492
493Each of the three bitwise operations has a different priority level:
494
495\begin{verbatim}
496and_expr: shift_expr | and_expr "&" shift_expr
497xor_expr: and_expr | xor_expr "^" and_expr
498or_expr: xor_expr | or_expr "|" xor_expr
499\end{verbatim}
500
Guido van Rossum6938f061994-08-01 12:22:53 +0000501The \verb@"&"@ operator yields the bitwise AND of its arguments, which
Guido van Rossum46f3e001992-08-14 09:11:01 +0000502must be plain or long integers. The arguments are converted to a
503common type.
504\indexii{bit-wise}{and}
505
Guido van Rossum6938f061994-08-01 12:22:53 +0000506The \verb@"^"@ operator yields the bitwise XOR (exclusive OR) of its
Guido van Rossum46f3e001992-08-14 09:11:01 +0000507arguments, which must be plain or long integers. The arguments are
508converted to a common type.
509\indexii{bit-wise}{xor}
510\indexii{exclusive}{or}
511
Guido van Rossum6938f061994-08-01 12:22:53 +0000512The \verb@"|"@ operator yields the bitwise (inclusive) OR of its
Guido van Rossum46f3e001992-08-14 09:11:01 +0000513arguments, which must be plain or long integers. The arguments are
514converted to a common type.
515\indexii{bit-wise}{or}
516\indexii{inclusive}{or}
517
518\section{Comparisons}
519\index{comparison}
520
521Contrary to C, all comparison operations in Python have the same
522priority, which is lower than that of any arithmetic, shifting or
523bitwise operation. Also contrary to C, expressions like
Guido van Rossum6938f061994-08-01 12:22:53 +0000524\verb@a < b < c@ have the interpretation that is conventional in
Guido van Rossum46f3e001992-08-14 09:11:01 +0000525mathematics:
526\index{C}
527
528\begin{verbatim}
529comparison: or_expr (comp_operator or_expr)*
530comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
531\end{verbatim}
532
533Comparisons yield integer values: 1 for true, 0 for false.
534
Guido van Rossuma5475471995-03-16 14:44:07 +0000535Comparisons can be chained arbitrarily, e.g. \code{x < y <= z} is
536equivalent to \code{x < y and y <= z}, except that \code{y} is
537evaluated only once (but in both cases \code{z} is not evaluated at all
538when \code{x < y} is found to be false).
Guido van Rossum46f3e001992-08-14 09:11:01 +0000539\indexii{chaining}{comparisons}
540
Guido van Rossuma5475471995-03-16 14:44:07 +0000541Formally, if \var{a}, \var{b}, \var{c}, \ldots, \var{y}, \var{z} are
542expressions and \var{opa}, \var{opb}, \ldots, \var{opy} are comparison
543operators, then \var{a opa b opb c} \ldots \var{y opy z} is equivalent
544to \var{a opa b} \code{and} \var{b opb c} \code{and} \ldots \code{and}
545\var{y opy z}, except that each expression is evaluated at most once.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000546
Guido van Rossuma5475471995-03-16 14:44:07 +0000547Note that \var{a opa b opb c} doesn't imply any kind of comparison
548between \var{a} and \var{c}, so that e.g.\ \code{x < y > z} is
549perfectly legal (though perhaps not pretty).
Guido van Rossum46f3e001992-08-14 09:11:01 +0000550
Guido van Rossum6938f061994-08-01 12:22:53 +0000551The forms \verb@<>@ and \verb@!=@ are equivalent; for consistency with
552C, \verb@!=@ is preferred; where \verb@!=@ is mentioned below
553\verb@<>@ is also implied.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000554
555The operators {\tt "<", ">", "==", ">=", "<="}, and {\tt "!="} compare
556the values of two objects. The objects needn't have the same type.
557If both are numbers, they are coverted to a common type. Otherwise,
558objects of different types {\em always} compare unequal, and are
559ordered consistently but arbitrarily.
560
561(This unusual definition of comparison is done to simplify the
Guido van Rossum6938f061994-08-01 12:22:53 +0000562definition of operations like sorting and the \verb@in@ and
Guido van Rossuma5475471995-03-16 14:44:07 +0000563\verb@not@ \verb@in@ operators.)
Guido van Rossum46f3e001992-08-14 09:11:01 +0000564
565Comparison of objects of the same type depends on the type:
566
567\begin{itemize}
568
569\item
570Numbers are compared arithmetically.
571
572\item
573Strings are compared lexicographically using the numeric equivalents
Guido van Rossum6938f061994-08-01 12:22:53 +0000574(the result of the built-in function \verb@ord@) of their characters.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000575
576\item
577Tuples and lists are compared lexicographically using comparison of
578corresponding items.
579
580\item
581Mappings (dictionaries) are compared through lexicographic
582comparison of their sorted (key, value) lists.%
583\footnote{This is expensive since it requires sorting the keys first,
Guido van Rossumb2c65561993-05-12 08:53:36 +0000584but about the only sensible definition. An earlier version of Python
585compared dictionaries by identity only, but this caused surprises
586because people expected to be able to test a dictionary for emptiness
587by comparing it to {\tt \{\}}.}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000588
589\item
590Most other types compare unequal unless they are the same object;
591the choice whether one object is considered smaller or larger than
592another one is made arbitrarily but consistently within one
593execution of a program.
594
595\end{itemize}
596
Guido van Rossum6938f061994-08-01 12:22:53 +0000597The operators \verb@in@ and \verb@not in@ test for sequence
Guido van Rossuma5475471995-03-16 14:44:07 +0000598membership: if \var{y} is a sequence, \code{\var{x} in \var{y}} is
599true if and only if there exists an index \var{i} such that
600\code{\var{x} = \var{y}[\var{i}]}.
601\code{\var{x} not in \var{y}} yields the inverse truth value. The
602exception \verb@TypeError@ is raised when \var{y} is not a sequence,
603or when \var{y} is a string and \var{x} is not a string of length one.%
Guido van Rossum46f3e001992-08-14 09:11:01 +0000604\footnote{The latter restriction is sometimes a nuisance.}
605\opindex{in}
606\opindex{not in}
607\indexii{membership}{test}
608\obindex{sequence}
609
Guido van Rossum6938f061994-08-01 12:22:53 +0000610The operators \verb@is@ and \verb@is not@ test for object identity:
Guido van Rossuma5475471995-03-16 14:44:07 +0000611\var{x} \code{is} \var{y} is true if and only if \var{x} and \var{y}
612are the same object. \var{x} \code{is not} \var{y} yields the inverse
613truth value.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000614\opindex{is}
615\opindex{is not}
616\indexii{identity}{test}
617
618\section{Boolean operations} \label{Booleans}
619\indexii{Boolean}{operation}
620
621Boolean operations have the lowest priority of all Python operations:
622
623\begin{verbatim}
Guido van Rossum3cbc16d1993-12-17 12:13:53 +0000624condition: or_test | lambda_form
Guido van Rossum46f3e001992-08-14 09:11:01 +0000625or_test: and_test | or_test "or" and_test
626and_test: not_test | and_test "and" not_test
627not_test: comparison | "not" not_test
Guido van Rossum3cbc16d1993-12-17 12:13:53 +0000628lambda_form: "lambda" [parameter_list]: condition
Guido van Rossum46f3e001992-08-14 09:11:01 +0000629\end{verbatim}
630
631In the context of Boolean operations, and also when conditions are
632used by control flow statements, the following values are interpreted
Guido van Rossum6938f061994-08-01 12:22:53 +0000633as false: \verb@None@, numeric zero of all types, empty sequences
Guido van Rossum46f3e001992-08-14 09:11:01 +0000634(strings, tuples and lists), and empty mappings (dictionaries). All
635other values are interpreted as true.
636
Guido van Rossum6938f061994-08-01 12:22:53 +0000637The operator \verb@not@ yields 1 if its argument is false, 0 otherwise.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000638\opindex{not}
639
Guido van Rossuma5475471995-03-16 14:44:07 +0000640The condition \var{x} \verb@and@ \var{y} first evaluates \var{x}; if
641\var{x} is false, its value is returned; otherwise, \var{y} is
642evaluated and the resulting value is returned.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000643\opindex{and}
644
Guido van Rossuma5475471995-03-16 14:44:07 +0000645The condition \var{x} \verb@or@ \var{y} first evaluates \var{x}; if
646\var{x} is true, its value is returned; otherwise, \var{y} is
647evaluated and the resulting value is returned.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000648\opindex{or}
649
Guido van Rossum6938f061994-08-01 12:22:53 +0000650(Note that \verb@and@ and \verb@or@ do not restrict the value and type
Guido van Rossum46f3e001992-08-14 09:11:01 +0000651they return to 0 and 1, but rather return the last evaluated argument.
Guido van Rossum6938f061994-08-01 12:22:53 +0000652This is sometimes useful, e.g. if \verb@s@ is a string that should be
Guido van Rossum46f3e001992-08-14 09:11:01 +0000653replaced by a default value if it is empty, the expression
Guido van Rossum6938f061994-08-01 12:22:53 +0000654\verb@s or 'foo'@ yields the desired value. Because \verb@not@ has to
Guido van Rossum46f3e001992-08-14 09:11:01 +0000655invent a value anyway, it does not bother to return a value of the
Guido van Rossum6938f061994-08-01 12:22:53 +0000656same type as its argument, so e.g. \verb@not 'foo'@ yields \verb@0@,
657not \verb@''@.)
Guido van Rossum46f3e001992-08-14 09:11:01 +0000658
Guido van Rossum3cbc16d1993-12-17 12:13:53 +0000659Lambda forms (lambda expressions) have the same syntactic position as
660conditions. They are a shorthand to create anonymous functions; the
Guido van Rossum6938f061994-08-01 12:22:53 +0000661expression {\em {\tt lambda} arguments{\tt :} condition}
Guido van Rossum3cbc16d1993-12-17 12:13:53 +0000662yields a function object that behaves virtually identical to one
Guido van Rossum6938f061994-08-01 12:22:53 +0000663defined with
664{\em {\tt def} name {\tt (}arguments{\tt ): return} condition}.
665See section \ref{function} for the syntax of
Guido van Rossum3cbc16d1993-12-17 12:13:53 +0000666parameter lists. Note that functions created with lambda forms cannot
667contain statements.
668\label{lambda}
669\indexii{lambda}{expression}
670\indexii{lambda}{form}
671\indexii{anonmymous}{function}
672
Guido van Rossum46f3e001992-08-14 09:11:01 +0000673\section{Expression lists and condition lists}
674\indexii{expression}{list}
675\indexii{condition}{list}
676
677\begin{verbatim}
678expr_list: or_expr ("," or_expr)* [","]
679cond_list: condition ("," condition)* [","]
680\end{verbatim}
681
682The only difference between expression lists and condition lists is
683the lowest priority of operators that can be used in them without
684being enclosed in parentheses; condition lists allow all operators,
685while expression lists don't allow comparisons and Boolean operators
686(they do allow bitwise and shift operators though).
687
688Expression lists are used in expression statements and assignments;
689condition lists are used everywhere else where a list of
690comma-separated values is required.
691
692An expression (condition) list containing at least one comma yields a
693tuple. The length of the tuple is the number of expressions
694(conditions) in the list. The expressions (conditions) are evaluated
Guido van Rossum16d6e711994-08-08 12:30:22 +0000695from left to right. (Condition lists are used syntactically is a few
Guido van Rossum46f3e001992-08-14 09:11:01 +0000696places where no tuple is constructed but a list of values is needed
697nevertheless.)
698\obindex{tuple}
699
700The trailing comma is required only to create a single tuple (a.k.a. a
701{\em singleton}); it is optional in all other cases. A single
702expression (condition) without a trailing comma doesn't create a
703tuple, but rather yields the value of that expression (condition).
704\indexii{trailing}{comma}
705
706(To create an empty tuple, use an empty pair of parentheses:
Guido van Rossum6938f061994-08-01 12:22:53 +0000707\verb@()@.)