blob: a4a7b530c25d0db5fcd36dac0d8802a1756c1a4e [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}
190
191A string conversion is a condition list enclosed in reverse (or
192backward) quotes:
193
194\begin{verbatim}
195string_conversion: "`" condition_list "`"
196\end{verbatim}
197
198A string conversion evaluates the contained condition list and
199converts the resulting object into a string according to rules
200specific to its type.
201
Guido van Rossum6938f061994-08-01 12:22:53 +0000202If the object is a string, a number, \verb@None@, or a tuple, list or
Guido van Rossum46f3e001992-08-14 09:11:01 +0000203dictionary containing only objects whose type is one of these, the
204resulting string is a valid Python expression which can be passed to
Guido van Rossum6938f061994-08-01 12:22:53 +0000205the built-in function \verb@eval()@ to yield an expression with the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000206same value (or an approximation, if floating point numbers are
207involved).
208
209(In particular, converting a string adds quotes around it and converts
210``funny'' characters to escape sequences that are safe to print.)
211
212It is illegal to attempt to convert recursive objects (e.g. lists or
213dictionaries that contain a reference to themselves, directly or
214indirectly.)
215\obindex{recursive}
216
217\section{Primaries} \label{primaries}
218\index{primary}
219
220Primaries represent the most tightly bound operations of the language.
221Their syntax is:
222
223\begin{verbatim}
224primary: atom | attributeref | subscription | slicing | call
225\end{verbatim}
226
227\subsection{Attribute references}
228\indexii{attribute}{reference}
229
230An attribute reference is a primary followed by a period and a name:
231
232\begin{verbatim}
233attributeref: primary "." identifier
234\end{verbatim}
235
236The primary must evaluate to an object of a type that supports
237attribute references, e.g. a module or a list. This object is then
238asked to produce the attribute whose name is the identifier. If this
Guido van Rossum6938f061994-08-01 12:22:53 +0000239attribute is not available, the exception \verb@AttributeError@ is
Guido van Rossum46f3e001992-08-14 09:11:01 +0000240raised. Otherwise, the type and value of the object produced is
241determined by the object. Multiple evaluations of the same attribute
242reference may yield different objects.
243\obindex{module}
244\obindex{list}
245
246\subsection{Subscriptions}
247\index{subscription}
248
249A subscription selects an item of a sequence (string, tuple or list)
250or mapping (dictionary) object:
251\obindex{sequence}
252\obindex{mapping}
253\obindex{string}
254\obindex{tuple}
255\obindex{list}
256\obindex{dictionary}
257\indexii{sequence}{item}
258
259\begin{verbatim}
260subscription: primary "[" condition "]"
261\end{verbatim}
262
263The primary must evaluate to an object of a sequence or mapping type.
264
265If it is a mapping, the condition must evaluate to an object whose
266value is one of the keys of the mapping, and the subscription selects
267the value in the mapping that corresponds to that key.
268
269If it is a sequence, the condition must evaluate to a plain integer.
270If this value is negative, the length of the sequence is added to it
Guido van Rossum6938f061994-08-01 12:22:53 +0000271(so that, e.g. \verb@x[-1]@ selects the last item of \verb@x@.)
Guido van Rossum46f3e001992-08-14 09:11:01 +0000272The resulting value must be a nonnegative integer smaller than the
273number of items in the sequence, and the subscription selects the item
274whose index is that value (counting from zero).
275
276A string's items are characters. A character is not a separate data
277type but a string of exactly one character.
278\index{character}
279\indexii{string}{item}
280
281\subsection{Slicings}
282\index{slicing}
283\index{slice}
284
285A slicing (or slice) selects a range of items in a sequence (string,
286tuple or list) object:
287\obindex{sequence}
288\obindex{string}
289\obindex{tuple}
290\obindex{list}
291
292\begin{verbatim}
293slicing: primary "[" [condition] ":" [condition] "]"
294\end{verbatim}
295
296The primary must evaluate to a sequence object. The lower and upper
297bound expressions, if present, must evaluate to plain integers;
298defaults are zero and the sequence's length, respectively. If either
299bound is negative, the sequence's length is added to it. The slicing
300now selects all items with index $k$ such that $i <= k < j$ where $i$
301and $j$ are the specified lower and upper bounds. This may be an
302empty sequence. It is not an error if $i$ or $j$ lie outside the
303range of valid indexes (such items don't exist so they aren't
304selected).
305
306\subsection{Calls} \label{calls}
307\index{call}
308
309A call calls a callable object (e.g. a function) with a possibly empty
310series of arguments:
311\obindex{callable}
312
313\begin{verbatim}
314call: primary "(" [condition_list] ")"
315\end{verbatim}
316
317The primary must evaluate to a callable object (user-defined
318functions, built-in functions, methods of built-in objects, class
319objects, and methods of class instances are callable). If it is a
320class, the argument list must be empty; otherwise, the arguments are
321evaluated.
322
Guido van Rossum6938f061994-08-01 12:22:53 +0000323A call always returns some value, possibly \verb@None@, unless it
Guido van Rossum46f3e001992-08-14 09:11:01 +0000324raises an exception. How this value is computed depends on the type
325of the callable object. If it is:
326
327\begin{description}
328
329\item[a user-defined function:] the code block for the function is
330executed, passing it the argument list. The first thing the code
331block will do is bind the formal parameters to the arguments; this is
332described in section \ref{function}. When the code block executes a
Guido van Rossum6938f061994-08-01 12:22:53 +0000333\verb@return@ statement, this specifies the return value of the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000334function call.
335\indexii{function}{call}
336\indexiii{user-defined}{function}{call}
337\obindex{user-defined function}
338\obindex{function}
339
340\item[a built-in function or method:] the result is up to the
341interpreter; see the library reference manual for the descriptions of
342built-in functions and methods.
343\indexii{function}{call}
344\indexii{built-in function}{call}
345\indexii{method}{call}
346\indexii{built-in method}{call}
347\obindex{built-in method}
348\obindex{built-in function}
349\obindex{method}
350\obindex{function}
351
352\item[a class object:] a new instance of that class is returned.
353\obindex{class}
354\indexii{class object}{call}
355
356\item[a class instance method:] the corresponding user-defined
357function is called, with an argument list that is one longer than the
358argument list of the call: the instance becomes the first argument.
359\obindex{class instance}
360\obindex{instance}
361\indexii{instance}{call}
362\indexii{class instance}{call}
363
364\end{description}
365
366\section{Unary arithmetic operations}
367\indexiii{unary}{arithmetic}{operation}
368\indexiii{unary}{bit-wise}{operation}
369
370All unary arithmetic (and bit-wise) operations have the same priority:
371
372\begin{verbatim}
373u_expr: primary | "-" u_expr | "+" u_expr | "~" u_expr
374\end{verbatim}
375
Guido van Rossum6938f061994-08-01 12:22:53 +0000376The unary \verb@"-"@ (minus) operator yields the negation of its
Guido van Rossum46f3e001992-08-14 09:11:01 +0000377numeric argument.
378\index{negation}
379\index{minus}
380
Guido van Rossum6938f061994-08-01 12:22:53 +0000381The unary \verb@"+"@ (plus) operator yields its numeric argument
Guido van Rossum46f3e001992-08-14 09:11:01 +0000382unchanged.
383\index{plus}
384
Guido van Rossum6938f061994-08-01 12:22:53 +0000385The unary \verb@"~"@ (invert) operator yields the bit-wise inversion
Guido van Rossum46f3e001992-08-14 09:11:01 +0000386of its plain or long integer argument. The bit-wise inversion of
Guido van Rossum6938f061994-08-01 12:22:53 +0000387\verb@x@ is defined as \verb@-(x+1)@.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000388\index{inversion}
389
390In all three cases, if the argument does not have the proper type,
Guido van Rossum6938f061994-08-01 12:22:53 +0000391a \verb@TypeError@ exception is raised.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000392\exindex{TypeError}
393
394\section{Binary arithmetic operations}
395\indexiii{binary}{arithmetic}{operation}
396
397The binary arithmetic operations have the conventional priority
398levels. Note that some of these operations also apply to certain
399non-numeric types. There is no ``power'' operator, so there are only
400two levels, one for multiplicative operators and one for additive
401operators:
402
403\begin{verbatim}
404m_expr: u_expr | m_expr "*" u_expr
405 | m_expr "/" u_expr | m_expr "%" u_expr
406a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
407\end{verbatim}
408
Guido van Rossum6938f061994-08-01 12:22:53 +0000409The \verb@"*"@ (multiplication) operator yields the product of its
Guido van Rossum46f3e001992-08-14 09:11:01 +0000410arguments. The arguments must either both be numbers, or one argument
411must be a plain integer and the other must be a sequence. In the
412former case, the numbers are converted to a common type and then
413multiplied together. In the latter case, sequence repetition is
414performed; a negative repetition factor yields an empty sequence.
415\index{multiplication}
416
Guido van Rossum6938f061994-08-01 12:22:53 +0000417The \verb@"/"@ (division) operator yields the quotient of its
Guido van Rossum46f3e001992-08-14 09:11:01 +0000418arguments. The numeric arguments are first converted to a common
419type. Plain or long integer division yields an integer of the same
420type; the result is that of mathematical division with the `floor'
421function applied to the result. Division by zero raises the
Guido van Rossum6938f061994-08-01 12:22:53 +0000422\verb@ZeroDivisionError@ exception.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000423\exindex{ZeroDivisionError}
424\index{division}
425
Guido van Rossum6938f061994-08-01 12:22:53 +0000426The \verb@"%"@ (modulo) operator yields the remainder from the
Guido van Rossum46f3e001992-08-14 09:11:01 +0000427division of the first argument by the second. The numeric arguments
428are first converted to a common type. A zero right argument raises
Guido van Rossum6938f061994-08-01 12:22:53 +0000429the \verb@ZeroDivisionError@ exception. The arguments may be floating
430point numbers, e.g. \verb@3.14 % 0.7@ equals \verb@0.34@. The modulo
Guido van Rossum46f3e001992-08-14 09:11:01 +0000431operator always yields a result with the same sign as its second
432operand (or zero); the absolute value of the result is strictly
433smaller than the second operand.
434\index{modulo}
435
436The integer division and modulo operators are connected by the
Guido van Rossum6938f061994-08-01 12:22:53 +0000437following identity: \verb@x == (x/y)*y + (x%y)@. Integer division and
438modulo are also connected with the built-in function \verb@divmod()@:
439\verb@divmod(x, y) == (x/y, x%y)@. These identities don't hold for
Guido van Rossum46f3e001992-08-14 09:11:01 +0000440floating point numbers; there a similar identity holds where
Guido van Rossum6938f061994-08-01 12:22:53 +0000441\verb@x/y@ is replaced by \verb@floor(x/y)@).
Guido van Rossum46f3e001992-08-14 09:11:01 +0000442
Guido van Rossum6938f061994-08-01 12:22:53 +0000443The \verb@"+"@ (addition) operator yields the sum of its arguments.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000444The arguments must either both be numbers, or both sequences of the
445same type. In the former case, the numbers are converted to a common
446type and then added together. In the latter case, the sequences are
447concatenated.
448\index{addition}
449
Guido van Rossum6938f061994-08-01 12:22:53 +0000450The \verb@"-"@ (subtraction) operator yields the difference of its
Guido van Rossum46f3e001992-08-14 09:11:01 +0000451arguments. The numeric arguments are first converted to a common
452type.
453\index{subtraction}
454
455\section{Shifting operations}
456\indexii{shifting}{operation}
457
458The shifting operations have lower priority than the arithmetic
459operations:
460
461\begin{verbatim}
462shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
463\end{verbatim}
464
465These operators accept plain or long integers as arguments. The
466arguments are converted to a common type. They shift the first
467argument to the left or right by the number of bits given by the
468second argument.
469
470A right shift by $n$ bits is defined as division by $2^n$. A left
471shift by $n$ bits is defined as multiplication with $2^n$; for plain
472integers there is no overflow check so this drops bits and flip the
473sign if the result is not less than $2^{31}$ in absolute value.
474
Guido van Rossum6938f061994-08-01 12:22:53 +0000475Negative shift counts raise a \verb@ValueError@ exception.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000476\exindex{ValueError}
477
478\section{Binary bit-wise operations}
479\indexiii{binary}{bit-wise}{operation}
480
481Each of the three bitwise operations has a different priority level:
482
483\begin{verbatim}
484and_expr: shift_expr | and_expr "&" shift_expr
485xor_expr: and_expr | xor_expr "^" and_expr
486or_expr: xor_expr | or_expr "|" xor_expr
487\end{verbatim}
488
Guido van Rossum6938f061994-08-01 12:22:53 +0000489The \verb@"&"@ operator yields the bitwise AND of its arguments, which
Guido van Rossum46f3e001992-08-14 09:11:01 +0000490must be plain or long integers. The arguments are converted to a
491common type.
492\indexii{bit-wise}{and}
493
Guido van Rossum6938f061994-08-01 12:22:53 +0000494The \verb@"^"@ operator yields the bitwise XOR (exclusive OR) of its
Guido van Rossum46f3e001992-08-14 09:11:01 +0000495arguments, which must be plain or long integers. The arguments are
496converted to a common type.
497\indexii{bit-wise}{xor}
498\indexii{exclusive}{or}
499
Guido van Rossum6938f061994-08-01 12:22:53 +0000500The \verb@"|"@ operator yields the bitwise (inclusive) OR of its
Guido van Rossum46f3e001992-08-14 09:11:01 +0000501arguments, which must be plain or long integers. The arguments are
502converted to a common type.
503\indexii{bit-wise}{or}
504\indexii{inclusive}{or}
505
506\section{Comparisons}
507\index{comparison}
508
509Contrary to C, all comparison operations in Python have the same
510priority, which is lower than that of any arithmetic, shifting or
511bitwise operation. Also contrary to C, expressions like
Guido van Rossum6938f061994-08-01 12:22:53 +0000512\verb@a < b < c@ have the interpretation that is conventional in
Guido van Rossum46f3e001992-08-14 09:11:01 +0000513mathematics:
514\index{C}
515
516\begin{verbatim}
517comparison: or_expr (comp_operator or_expr)*
518comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"
519\end{verbatim}
520
521Comparisons yield integer values: 1 for true, 0 for false.
522
523Comparisons can be chained arbitrarily, e.g. $x < y <= z$ is
Guido van Rossum6938f061994-08-01 12:22:53 +0000524equivalent to $x < y$ \verb@and@ $y <= z$, except that $y$ is
Guido van Rossum46f3e001992-08-14 09:11:01 +0000525evaluated only once (but in both cases $z$ is not evaluated at all
526when $x < y$ is found to be false).
527\indexii{chaining}{comparisons}
528
Guido van Rossum4ac605e1992-12-17 15:31:02 +0000529\catcode`\_=8
Guido van Rossum46f3e001992-08-14 09:11:01 +0000530Formally, $e_0 op_1 e_1 op_2 e_2 ...e_{n-1} op_n e_n$ is equivalent to
Guido van Rossum6938f061994-08-01 12:22:53 +0000531$e_0 op_1 e_1$ \verb@and@ $e_1 op_2 e_2$ \verb@and@ ... \verb@and@
Guido van Rossum46f3e001992-08-14 09:11:01 +0000532$e_{n-1} op_n e_n$, except that each expression is evaluated at most once.
533
534Note that $e_0 op_1 e_1 op_2 e_2$ does not imply any kind of comparison
535between $e_0$ and $e_2$, e.g. $x < y > z$ is perfectly legal.
Guido van Rossum4ac605e1992-12-17 15:31:02 +0000536\catcode`\_=12
Guido van Rossum46f3e001992-08-14 09:11:01 +0000537
Guido van Rossum6938f061994-08-01 12:22:53 +0000538The forms \verb@<>@ and \verb@!=@ are equivalent; for consistency with
539C, \verb@!=@ is preferred; where \verb@!=@ is mentioned below
540\verb@<>@ is also implied.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000541
542The operators {\tt "<", ">", "==", ">=", "<="}, and {\tt "!="} compare
543the values of two objects. The objects needn't have the same type.
544If both are numbers, they are coverted to a common type. Otherwise,
545objects of different types {\em always} compare unequal, and are
546ordered consistently but arbitrarily.
547
548(This unusual definition of comparison is done to simplify the
Guido van Rossum6938f061994-08-01 12:22:53 +0000549definition of operations like sorting and the \verb@in@ and
550\verb@not in@ operators.)
Guido van Rossum46f3e001992-08-14 09:11:01 +0000551
552Comparison of objects of the same type depends on the type:
553
554\begin{itemize}
555
556\item
557Numbers are compared arithmetically.
558
559\item
560Strings are compared lexicographically using the numeric equivalents
Guido van Rossum6938f061994-08-01 12:22:53 +0000561(the result of the built-in function \verb@ord@) of their characters.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000562
563\item
564Tuples and lists are compared lexicographically using comparison of
565corresponding items.
566
567\item
568Mappings (dictionaries) are compared through lexicographic
569comparison of their sorted (key, value) lists.%
570\footnote{This is expensive since it requires sorting the keys first,
Guido van Rossumb2c65561993-05-12 08:53:36 +0000571but about the only sensible definition. An earlier version of Python
572compared dictionaries by identity only, but this caused surprises
573because people expected to be able to test a dictionary for emptiness
574by comparing it to {\tt \{\}}.}
Guido van Rossum46f3e001992-08-14 09:11:01 +0000575
576\item
577Most other types compare unequal unless they are the same object;
578the choice whether one object is considered smaller or larger than
579another one is made arbitrarily but consistently within one
580execution of a program.
581
582\end{itemize}
583
Guido van Rossum6938f061994-08-01 12:22:53 +0000584The operators \verb@in@ and \verb@not in@ test for sequence
585membership: if $y$ is a sequence, $x ~\verb@in@~ y$ is true if and
Guido van Rossum46f3e001992-08-14 09:11:01 +0000586only if there exists an index $i$ such that $x = y[i]$.
Guido van Rossum6938f061994-08-01 12:22:53 +0000587$x ~\verb@not in@~ y$ yields the inverse truth value. The exception
588\verb@TypeError@ is raised when $y$ is not a sequence, or when $y$ is
Guido van Rossum46f3e001992-08-14 09:11:01 +0000589a string and $x$ is not a string of length one.%
590\footnote{The latter restriction is sometimes a nuisance.}
591\opindex{in}
592\opindex{not in}
593\indexii{membership}{test}
594\obindex{sequence}
595
Guido van Rossum6938f061994-08-01 12:22:53 +0000596The operators \verb@is@ and \verb@is not@ test for object identity:
597$x ~\verb@is@~ y$ is true if and only if $x$ and $y$ are the same
598object. $x ~\verb@is not@~ y$ yields the inverse truth value.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000599\opindex{is}
600\opindex{is not}
601\indexii{identity}{test}
602
603\section{Boolean operations} \label{Booleans}
604\indexii{Boolean}{operation}
605
606Boolean operations have the lowest priority of all Python operations:
607
608\begin{verbatim}
Guido van Rossum3cbc16d1993-12-17 12:13:53 +0000609condition: or_test | lambda_form
Guido van Rossum46f3e001992-08-14 09:11:01 +0000610or_test: and_test | or_test "or" and_test
611and_test: not_test | and_test "and" not_test
612not_test: comparison | "not" not_test
Guido van Rossum3cbc16d1993-12-17 12:13:53 +0000613lambda_form: "lambda" [parameter_list]: condition
Guido van Rossum46f3e001992-08-14 09:11:01 +0000614\end{verbatim}
615
616In the context of Boolean operations, and also when conditions are
617used by control flow statements, the following values are interpreted
Guido van Rossum6938f061994-08-01 12:22:53 +0000618as false: \verb@None@, numeric zero of all types, empty sequences
Guido van Rossum46f3e001992-08-14 09:11:01 +0000619(strings, tuples and lists), and empty mappings (dictionaries). All
620other values are interpreted as true.
621
Guido van Rossum6938f061994-08-01 12:22:53 +0000622The operator \verb@not@ yields 1 if its argument is false, 0 otherwise.
Guido van Rossum46f3e001992-08-14 09:11:01 +0000623\opindex{not}
624
Guido van Rossum6938f061994-08-01 12:22:53 +0000625The condition $x ~\verb@and@~ y$ first evaluates $x$; if $x$ is false,
Guido van Rossum46f3e001992-08-14 09:11:01 +0000626its value is returned; otherwise, $y$ is evaluated and the resulting
627value is returned.
628\opindex{and}
629
Guido van Rossum6938f061994-08-01 12:22:53 +0000630The condition $x ~\verb@or@~ y$ first evaluates $x$; if $x$ is true,
Guido van Rossum46f3e001992-08-14 09:11:01 +0000631its value is returned; otherwise, $y$ is evaluated and the resulting
632value is returned.
633\opindex{or}
634
Guido van Rossum6938f061994-08-01 12:22:53 +0000635(Note that \verb@and@ and \verb@or@ do not restrict the value and type
Guido van Rossum46f3e001992-08-14 09:11:01 +0000636they return to 0 and 1, but rather return the last evaluated argument.
Guido van Rossum6938f061994-08-01 12:22:53 +0000637This is sometimes useful, e.g. if \verb@s@ is a string that should be
Guido van Rossum46f3e001992-08-14 09:11:01 +0000638replaced by a default value if it is empty, the expression
Guido van Rossum6938f061994-08-01 12:22:53 +0000639\verb@s or 'foo'@ yields the desired value. Because \verb@not@ has to
Guido van Rossum46f3e001992-08-14 09:11:01 +0000640invent a value anyway, it does not bother to return a value of the
Guido van Rossum6938f061994-08-01 12:22:53 +0000641same type as its argument, so e.g. \verb@not 'foo'@ yields \verb@0@,
642not \verb@''@.)
Guido van Rossum46f3e001992-08-14 09:11:01 +0000643
Guido van Rossum3cbc16d1993-12-17 12:13:53 +0000644Lambda forms (lambda expressions) have the same syntactic position as
645conditions. They are a shorthand to create anonymous functions; the
Guido van Rossum6938f061994-08-01 12:22:53 +0000646expression {\em {\tt lambda} arguments{\tt :} condition}
Guido van Rossum3cbc16d1993-12-17 12:13:53 +0000647yields a function object that behaves virtually identical to one
Guido van Rossum6938f061994-08-01 12:22:53 +0000648defined with
649{\em {\tt def} name {\tt (}arguments{\tt ): return} condition}.
650See section \ref{function} for the syntax of
Guido van Rossum3cbc16d1993-12-17 12:13:53 +0000651parameter lists. Note that functions created with lambda forms cannot
652contain statements.
653\label{lambda}
654\indexii{lambda}{expression}
655\indexii{lambda}{form}
656\indexii{anonmymous}{function}
657
Guido van Rossum46f3e001992-08-14 09:11:01 +0000658\section{Expression lists and condition lists}
659\indexii{expression}{list}
660\indexii{condition}{list}
661
662\begin{verbatim}
663expr_list: or_expr ("," or_expr)* [","]
664cond_list: condition ("," condition)* [","]
665\end{verbatim}
666
667The only difference between expression lists and condition lists is
668the lowest priority of operators that can be used in them without
669being enclosed in parentheses; condition lists allow all operators,
670while expression lists don't allow comparisons and Boolean operators
671(they do allow bitwise and shift operators though).
672
673Expression lists are used in expression statements and assignments;
674condition lists are used everywhere else where a list of
675comma-separated values is required.
676
677An expression (condition) list containing at least one comma yields a
678tuple. The length of the tuple is the number of expressions
679(conditions) in the list. The expressions (conditions) are evaluated
Guido van Rossum16d6e711994-08-08 12:30:22 +0000680from left to right. (Condition lists are used syntactically is a few
Guido van Rossum46f3e001992-08-14 09:11:01 +0000681places where no tuple is constructed but a list of values is needed
682nevertheless.)
683\obindex{tuple}
684
685The trailing comma is required only to create a single tuple (a.k.a. a
686{\em singleton}); it is optional in all other cases. A single
687expression (condition) without a trailing comma doesn't create a
688tuple, but rather yields the value of that expression (condition).
689\indexii{trailing}{comma}
690
691(To create an empty tuple, use an empty pair of parentheses:
Guido van Rossum6938f061994-08-01 12:22:53 +0000692\verb@()@.)