1 \chapter{Expressions
\label{expressions
}}
4 This chapter explains the meaning of the elements of expressions in
7 \strong{Syntax Notes:
} In this and the following chapters, extended
8 BNF
\index{BNF
} notation will be used to describe syntax, not lexical
9 analysis. When (one alternative of) a syntax rule has the form
15 and no semantics are given, the semantics of this form of
\code{name
}
16 are the same as for
\code{othername
}.
19 \section{Arithmetic conversions
\label{conversions
}}
20 \indexii{arithmetic
}{conversion
}
22 When a description of an arithmetic operator below uses the phrase
23 ``the numeric arguments are converted to a common type,'' the
24 arguments are coerced using the coercion rules listed at the end of
25 chapter
3. If both arguments are standard numeric types, the
26 following coercions are applied:
29 \item If either argument is a complex number, the other is converted
31 \item otherwise, if either argument is a floating point number,
32 the other is converted to floating point;
33 \item otherwise, if either argument is a long integer,
34 the other is converted to long integer;
35 \item otherwise, both must be plain integers and no conversion
39 Some additional rules apply for certain operators (e.g., a string left
40 argument to the `\%' operator). Extensions can define their own
44 \section{Atoms
\label{atoms
}}
47 Atoms are the most basic elements of expressions. The simplest atoms
48 are identifiers or literals. Forms enclosed in
49 reverse quotes or in parentheses, brackets or braces are also
50 categorized syntactically as atoms. The syntax for atoms is:
53 atom: identifier | literal | enclosure
54 enclosure: parenth_form|list_display|dict_display|string_conversion
57 \subsection{Identifiers (Names)
\label{atom-identifiers
}}
61 An identifier occurring as an atom is a reference to a local, global
62 or built-in name binding. If a name is assigned to anywhere in a code
63 block (even in unreachable code), and is not mentioned in a
64 \keyword{global
} statement in that code block, then it refers to a local
65 name throughout that code block. When it is not assigned to anywhere
66 in the block, or when it is assigned to but also explicitly listed in
67 a
\keyword{global
} statement, it refers to a global name if one exists,
68 else to a built-in name (and this binding may dynamically
69 change).
\footnote{The Python interpreter provides a useful set of
70 predefined built-in functions. It is not recommended to reuse
71 (hide) these names with self defined objects. See the
72 \citetitle[../lib/built-in-funcs.html
]{Python Library Reference
} for
73 the descriptions of built-in functions and methods.
}
74 \indexii{name
}{binding
}
77 \indexii{built-in
}{name
}
78 \indexii{global
}{name
}
80 When the name is bound to an object, evaluation of the atom yields
81 that object. When a name is not bound, an attempt to evaluate it
82 raises a
\exception{NameError
} exception.
85 \strong{Private name mangling:
}%
86 \indexii{name
}{mangling
}%
87 \indexii{private
}{names
}%
88 when an identifier that textually occurs in a class definition begins
89 with two or more underscore characters and does not end in two or more
90 underscores, it is considered a
\dfn{private name
} of that class.
91 Private names are transformed to a longer form before code is
92 generated for them. The transformation inserts the class name in
93 front of the name, with leading underscores removed, and a single
94 underscore inserted in front of the class name. For example, the
95 identifier
\code{__spam
} occurring in a class named
\code{Ham
} will be
96 transformed to
\code{_Ham__spam
}. This transformation is independent
97 of the syntactical context in which the identifier is used. If the
98 transformed name is extremely long (longer than
255 characters),
99 implementation defined truncation may happen. If the class name
100 consists only of underscores, no transformation is done.
102 \subsection{Literals
\label{atom-literals
}}
105 Python supports string literals and various numeric literals:
108 literal: stringliteral | integer | longinteger | floatnumber | imagnumber
111 Evaluation of a literal yields an object of the given type (string,
112 integer, long integer, floating point number, complex number) with the
113 given value. The value may be approximated in the case of floating
114 point and imaginary (complex) literals. See section
\ref{literals
}
117 All literals correspond to immutable data types, and hence the
118 object's identity is less important than its value. Multiple
119 evaluations of literals with the same value (either the same
120 occurrence in the program text or a different occurrence) may obtain
121 the same object or a different object with the same value.
122 \indexiii{immutable
}{data
}{type
}
123 \indexii{immutable
}{object
}
125 \subsection{Parenthesized forms
\label{parenthesized
}}
126 \index{parenthesized form
}
128 A parenthesized form is an optional expression list enclosed in
132 parenth_form: "("
[expression_list
] ")"
135 A parenthesized expression list yields whatever that expression list
136 yields: if the list contains at least one comma, it yields a tuple;
137 otherwise, it yields the single expression that makes up the
140 An empty pair of parentheses yields an empty tuple object. Since
141 tuples are immutable, the rules for literals apply (i.e., two
142 occurrences of the empty tuple may or may not yield the same object).
143 \indexii{empty
}{tuple
}
145 Note that tuples are not formed by the parentheses, but rather by use
146 of the comma operator. The exception is the empty tuple, for which
147 parentheses
\emph{are
} required --- allowing unparenthesized ``nothing''
148 in expressions would cause ambiguities and allow common typos to
151 \indexii{tuple
}{display
}
153 \subsection{List displays
\label{lists
}}
154 \indexii{list
}{display
}
155 \indexii{list
}{comprehensions
}
157 A list display is a possibly empty series of expressions enclosed in
161 list_display: "
["
[listmaker
] "
]"
162 listmaker: expression ( list_for | ( "," expression)*
[","
] )
163 list_iter: list_for | list_if
164 list_for: "for" expression_list "in" testlist
[list_iter
]
165 list_if: "if" test
[list_iter
]
168 A list display yields a new list object. Its contents are specified
169 by providing either a list of expressions or a list comprehension.
170 \indexii{list
}{comprehensions
}
171 When a comma-separated list of expressions is supplied, its elements are
172 evaluated from left to right and placed into the list object in that
173 order. When a list comprehension is supplied, it consists of a
174 single expression followed by at least one
\keyword{for
} clause and zero or
175 more
\keyword{for
} or
\keyword{if
} clauses. In this
176 case, the elements of the new list are those that would be produced
177 by considering each of the
\keyword{for
} or
\keyword{if
} clauses a block,
179 left to right, and evaluating the expression to produce a list element
180 each time the innermost block is reached.
182 \indexii{empty
}{list
}
184 \subsection{Dictionary displays
\label{dict
}}
185 \indexii{dictionary
}{display
}
187 A dictionary display is a possibly empty series of key/datum pairs
188 enclosed in curly braces:
191 \index{key/datum pair
}
194 dict_display: "
{"
[key_datum_list
] "
}"
195 key_datum_list: key_datum ("," key_datum)*
[","
]
196 key_datum: expression ":" expression
199 A dictionary display yields a new dictionary object.
202 The key/datum pairs are evaluated from left to right to define the
203 entries of the dictionary: each key object is used as a key into the
204 dictionary to store the corresponding datum.
206 Restrictions on the types of the key values are listed earlier in
207 section
\ref{types
}. (To summarize,the key type should be hashable,
208 which excludes all mutable objects.) Clashes between duplicate keys
209 are not detected; the last datum (textually rightmost in the display)
210 stored for a given key value prevails.
211 \indexii{immutable
}{object
}
213 \subsection{String conversions
\label{string-conversions
}}
214 \indexii{string
}{conversion
}
215 \indexii{reverse
}{quotes
}
216 \indexii{backward
}{quotes
}
219 A string conversion is an expression list enclosed in reverse (a.k.a.
223 string_conversion: "`" expression_list "`"
226 A string conversion evaluates the contained expression list and
227 converts the resulting object into a string according to rules
228 specific to its type.
230 If the object is a string, a number,
\code{None
}, or a tuple, list or
231 dictionary containing only objects whose type is one of these, the
232 resulting string is a valid Python expression which can be passed to
233 the built-in function
\function{eval()
} to yield an expression with the
234 same value (or an approximation, if floating point numbers are
237 (In particular, converting a string adds quotes around it and converts
238 ``funny'' characters to escape sequences that are safe to print.)
240 It is illegal to attempt to convert recursive objects (e.g., lists or
241 dictionaries that contain a reference to themselves, directly or
245 The built-in function
\function{repr()
} performs exactly the same
246 conversion in its argument as enclosing it in parentheses and reverse
247 quotes does. The built-in function
\function{str()
} performs a
248 similar but more user-friendly conversion.
252 \section{Primaries
\label{primaries
}}
255 Primaries represent the most tightly bound operations of the language.
259 primary: atom | attributeref | subscription | slicing | call
262 \subsection{Attribute references
\label{attribute-references
}}
263 \indexii{attribute
}{reference
}
265 An attribute reference is a primary followed by a period and a name:
268 attributeref: primary "." identifier
271 The primary must evaluate to an object of a type that supports
272 attribute references, e.g., a module, list, or an instance. This
273 object is then asked to produce the attribute whose name is the
274 identifier. If this attribute is not available, the exception
275 \exception{AttributeError
}\exindex{AttributeError
} is raised.
276 Otherwise, the type and value of the object produced is determined by
277 the object. Multiple evaluations of the same attribute reference may
278 yield different objects.
282 \subsection{Subscriptions
\label{subscriptions
}}
285 A subscription selects an item of a sequence (string, tuple or list)
286 or mapping (dictionary) object:
293 \indexii{sequence
}{item
}
296 subscription: primary "
[" expression_list "
]"
299 The primary must evaluate to an object of a sequence or mapping type.
301 If the primary is a mapping, the expression list must evaluate to an
302 object whose value is one of the keys of the mapping, and the
303 subscription selects the value in the mapping that corresponds to that
304 key. (The expression list is a tuple except if it has exactly one
307 If the primary is a sequence, the expression (list) must evaluate to a
308 plain integer. If this value is negative, the length of the sequence
309 is added to it (so that, e.g.,
\code{x
[-
1]} selects the last item of
310 \code{x
}.) The resulting value must be a nonnegative integer less
311 than the number of items in the sequence, and the subscription selects
312 the item whose index is that value (counting from zero).
314 A string's items are characters. A character is not a separate data
315 type but a string of exactly one character.
317 \indexii{string
}{item
}
319 \subsection{Slicings
\label{slicings
}}
323 A slicing selects a range of items in a sequence object (e.g., a
324 string, tuple or list). Slicings may be used as expressions or as
325 targets in assignment or del statements. The syntax for a slicing:
332 slicing: simple_slicing | extended_slicing
333 simple_slicing: primary "
[" short_slice "
]"
334 extended_slicing: primary "
[" slice_list "
]"
335 slice_list: slice_item ("," slice_item)*
[","
]
336 slice_item: expression | proper_slice | ellipsis
337 proper_slice: short_slice | long_slice
338 short_slice:
[lower_bound
] ":"
[upper_bound
]
339 long_slice: short_slice ":"
[stride
]
340 lower_bound: expression
341 upper_bound: expression
346 There is ambiguity in the formal syntax here: anything that looks like
347 an expression list also looks like a slice list, so any subscription
348 can be interpreted as a slicing. Rather than further complicating the
349 syntax, this is disambiguated by defining that in this case the
350 interpretation as a subscription takes priority over the
351 interpretation as a slicing (this is the case if the slice list
352 contains no proper slice nor ellipses). Similarly, when the slice
353 list has exactly one short slice and no trailing comma, the
354 interpretation as a simple slicing takes priority over that as an
355 extended slicing.
\indexii{extended
}{slicing
}
357 The semantics for a simple slicing are as follows. The primary must
358 evaluate to a sequence object. The lower and upper bound expressions,
359 if present, must evaluate to plain integers; defaults are zero and the
360 \code{sys.maxint
}, respectively. If either bound is negative, the
361 sequence's length is added to it. The slicing now selects all items
362 with index
\var{k
} such that
363 \code{\var{i
} <=
\var{k
} <
\var{j
}} where
\var{i
}
364 and
\var{j
} are the specified lower and upper bounds. This may be an
365 empty sequence. It is not an error if
\var{i
} or
\var{j
} lie outside the
366 range of valid indexes (such items don't exist so they aren't
369 The semantics for an extended slicing are as follows. The primary
370 must evaluate to a mapping object, and it is indexed with a key that
371 is constructed from the slice list, as follows. If the slice list
372 contains at least one comma, the key is a tuple containing the
373 conversion of the slice items; otherwise, the conversion of the lone
374 slice item is the key. The conversion of a slice item that is an
375 expression is that expression. The conversion of an ellipsis slice
376 item is the built-in
\code{Ellipsis
} object. The conversion of a
377 proper slice is a slice object (see section
\ref{types
}) whose
378 \member{start
},
\member{stop
} and
\member{step
} attributes are the
379 values of the expressions given as lower bound, upper bound and
380 stride, respectively, substituting
\code{None
} for missing
382 \withsubitem{(slice object attribute)
}{\ttindex{start
}
383 \ttindex{stop
}\ttindex{step
}}
385 \subsection{Calls
\label{calls
}}
388 A call calls a callable object (e.g., a function) with a possibly empty
393 call: primary "("
[argument_list
[","
]] ")"
394 argument_list: positional_arguments
["," keyword_arguments
]
396 positional_arguments: expression ("," expression)*
397 keyword_arguments: keyword_item ("," keyword_item)*
398 keyword_item: identifier "=" expression
401 A trailing comma may be present after an argument list but does not
402 affect the semantics.
404 The primary must evaluate to a callable object (user-defined
405 functions, built-in functions, methods of built-in objects, class
406 objects, methods of class instances, and certain class instances
407 themselves are callable; extensions may define additional callable
408 object types). All argument expressions are evaluated before the call
409 is attempted. Please refer to section
\ref{function
} for the syntax
410 of formal parameter lists.
412 If keyword arguments are present, they are first converted to
413 positional arguments, as follows. First, a list of unfilled slots is
414 created for the formal parameters. If there are N positional
415 arguments, they are placed in the first N slots. Next, for each
416 keyword argument, the identifier is used to determine the
417 corresponding slot (if the identifier is the same as the first formal
418 parameter name, the first slot is used, and so on). If the slot is
419 already filled, a
\exception{TypeError
} exception is raised.
420 Otherwise, the value of the argument is placed in the slot, filling it
421 (even if the expression is
\code{None
}, it fills the slot). When all
422 arguments have been processed, the slots that are still unfilled are
423 filled with the corresponding default value from the function
424 definition. (Default values are calculated, once, when the function
425 is defined; thus, a mutable object such as a list or dictionary used
426 as default value will be shared by all calls that don't specify an
427 argument value for the corresponding slot; this should usually be
428 avoided.) If there are any unfilled slots for which no default value
429 is specified, a
\exception{TypeError
} exception is raised. Otherwise,
430 the list of filled slots is used as the argument list for the call.
432 If there are more positional arguments than there are formal parameter
433 slots, a
\exception{TypeError
} exception is raised, unless a formal
434 parameter using the syntax
\samp{*identifier
} is present; in this
435 case, that formal parameter receives a tuple containing the excess
436 positional arguments (or an empty tuple if there were no excess
437 positional arguments).
439 If any keyword argument does not correspond to a formal parameter
440 name, a
\exception{TypeError
} exception is raised, unless a formal
441 parameter using the syntax
\samp{**identifier
} is present; in this
442 case, that formal parameter receives a dictionary containing the
443 excess keyword arguments (using the keywords as keys and the argument
444 values as corresponding values), or a (new) empty dictionary if there
445 were no excess keyword arguments.
447 Formal parameters using the syntax
\samp{*identifier
} or
448 \samp{**identifier
} cannot be used as positional argument slots or
449 as keyword argument names. Formal parameters using the syntax
450 \samp{(sublist)
} cannot be used as keyword argument names; the
451 outermost sublist corresponds to a single unnamed argument slot, and
452 the argument value is assigned to the sublist using the usual tuple
453 assignment rules after all other parameter processing is done.
455 A call always returns some value, possibly
\code{None
}, unless it
456 raises an exception. How this value is computed depends on the type
457 of the callable object.
463 \item[a user-defined function:
] The code block for the function is
464 executed, passing it the argument list. The first thing the code
465 block will do is bind the formal parameters to the arguments; this is
466 described in section
\ref{function
}. When the code block executes a
467 \keyword{return
} statement, this specifies the return value of the
469 \indexii{function
}{call
}
470 \indexiii{user-defined
}{function
}{call
}
471 \obindex{user-defined function
}
474 \item[a built-in function or method:
] The result is up to the
475 interpreter; see the
\citetitle[../lib/built-in-funcs.html
]{Python
476 Library Reference
} for the descriptions of built-in functions and
478 \indexii{function
}{call
}
479 \indexii{built-in function
}{call
}
480 \indexii{method
}{call
}
481 \indexii{built-in method
}{call
}
482 \obindex{built-in method
}
483 \obindex{built-in function
}
487 \item[a class object:
] A new instance of that class is returned.
489 \indexii{class object
}{call
}
491 \item[a class instance method:
] The corresponding user-defined
492 function is called, with an argument list that is one longer than the
493 argument list of the call: the instance becomes the first argument.
494 \obindex{class instance
}
496 \indexii{class instance
}{call
}
498 \item[a class instance:
] The class must define a
\method{__call__()
}
499 method; the effect is then the same as if that method was called.
500 \indexii{instance
}{call
}
501 \withsubitem{(object method)
}{\ttindex{__call__()
}}
506 \section{The power operator
\label{power
}}
508 The power operator binds more tightly than unary operators on its
509 left; it binds less tightly than unary operators on its right. The
513 power: primary
["**" u_expr
]
516 Thus, in an unparenthesized sequence of power and unary operators, the
517 operators are evaluated from right to left (this does not constrain
518 the evaluation order for the operands).
520 The power operator has the same semantics as the built-in
521 \function{pow()
} function, when called with two arguments: it yields
522 its left argument raised to the power of its right argument. The
523 numeric arguments are first converted to a common type. The result
524 type is that of the arguments after coercion; if the result is not
525 expressible in that type (as in raising an integer to a negative
526 power, or a negative floating point number to a broken power), a
527 \exception{TypeError
} exception is raised.
530 \section{Unary arithmetic operations
\label{unary
}}
531 \indexiii{unary
}{arithmetic
}{operation
}
532 \indexiii{unary
}{bit-wise
}{operation
}
534 All unary arithmetic (and bit-wise) operations have the same priority:
537 u_expr: power | "-" u_expr | "+" u_expr | "~" u_expr
540 The unary
\code{-
} (minus) operator yields the negation of its
545 The unary
\code{+
} (plus) operator yields its numeric argument
549 The unary
\code{\~
} (invert) operator yields the bit-wise inversion
550 of its plain or long integer argument. The bit-wise inversion of
551 \code{x
} is defined as
\code{-(x+
1)
}. It only applies to integral
555 In all three cases, if the argument does not have the proper type,
556 a
\exception{TypeError
} exception is raised.
559 \section{Binary arithmetic operations
\label{binary
}}
560 \indexiii{binary
}{arithmetic
}{operation
}
562 The binary arithmetic operations have the conventional priority
563 levels. Note that some of these operations also apply to certain
564 non-numeric types. Apart from the power operator, there are only two
565 levels, one for multiplicative operators and one for additive
569 m_expr: u_expr | m_expr "*" u_expr
570 | m_expr "/" u_expr | m_expr "
%" u_expr
571 a_expr: m_expr | aexpr "+" m_expr | aexpr "-" m_expr
574 The
\code{*
} (multiplication) operator yields the product of its
575 arguments. The arguments must either both be numbers, or one argument
576 must be an integer (plain or long) and the other must be a sequence.
577 In the former case, the numbers are converted to a common type and
578 then multiplied together. In the latter case, sequence repetition is
579 performed; a negative repetition factor yields an empty sequence.
580 \index{multiplication
}
582 The
\code{/
} (division) operator yields the quotient of its
583 arguments. The numeric arguments are first converted to a common
584 type. Plain or long integer division yields an integer of the same
585 type; the result is that of mathematical division with the `floor'
586 function applied to the result. Division by zero raises the
587 \exception{ZeroDivisionError
} exception.
588 \exindex{ZeroDivisionError
}
591 The
\code{\%
} (modulo) operator yields the remainder from the
592 division of the first argument by the second. The numeric arguments
593 are first converted to a common type. A zero right argument raises
594 the
\exception{ZeroDivisionError
} exception. The arguments may be floating
595 point numbers, e.g.,
\code{3.14\%
0.7} equals
\code{0.34} (since
596 \code{3.14} equals
\code{4*
0.7 +
0.34}.) The modulo operator always
597 yields a result with the same sign as its second operand (or zero);
598 the absolute value of the result is strictly smaller than the second
602 The integer division and modulo operators are connected by the
603 following identity:
\code{x == (x/y)*y + (x\%y)
}. Integer division and
604 modulo are also connected with the built-in function
\function{divmod()
}:
605 \code{divmod(x, y) == (x/y, x\%y)
}. These identities don't hold for
606 floating point and complex numbers; there similar identities hold
607 approximately where
\code{x/y
} is replaced by
\code{floor(x/y)
}) or
608 \code{floor(x/y) -
1} (for floats),
\footnote{
609 If x is very close to an exact integer multiple of y, it's
610 possible for
\code{floor(x/y)
} to be one larger than
611 \code{(x-x\%y)/y
} due to rounding. In such cases, Python returns
612 the latter result, in order to preserve that
\code{divmod(x,y)
[0]
613 * y + x \%
{} y
} be very close to
\code{x
}.
614 } or
\code{floor((x/y).real)
} (for
617 The
\code{+
} (addition) operator yields the sum of its arguments.
618 The arguments must either both be numbers or both sequences of the
619 same type. In the former case, the numbers are converted to a common
620 type and then added together. In the latter case, the sequences are
624 The
\code{-
} (subtraction) operator yields the difference of its
625 arguments. The numeric arguments are first converted to a common
629 \section{Shifting operations
\label{shifting
}}
630 \indexii{shifting
}{operation
}
632 The shifting operations have lower priority than the arithmetic
636 shift_expr: a_expr | shift_expr ( "<<" | ">>" ) a_expr
639 These operators accept plain or long integers as arguments. The
640 arguments are converted to a common type. They shift the first
641 argument to the left or right by the number of bits given by the
644 A right shift by
\var{n
} bits is defined as division by
645 \code{pow(
2,
\var{n
})
}. A left shift by
\var{n
} bits is defined as
646 multiplication with
\code{pow(
2,
\var{n
})
}; for plain integers there is
647 no overflow check so in that case the operation drops bits and flips
648 the sign if the result is not less than
\code{pow(
2,
31)
} in absolute
649 value. Negative shift counts raise a
\exception{ValueError
}
653 \section{Binary bit-wise operations
\label{bitwise
}}
654 \indexiii{binary
}{bit-wise
}{operation
}
656 Each of the three bitwise operations has a different priority level:
659 and_expr: shift_expr | and_expr "&" shift_expr
660 xor_expr: and_expr | xor_expr "^" and_expr
661 or_expr: xor_expr | or_expr "|" xor_expr
664 The
\code{\&
} operator yields the bitwise AND of its arguments, which
665 must be plain or long integers. The arguments are converted to a
667 \indexii{bit-wise
}{and
}
669 The
\code{\^
} operator yields the bitwise XOR (exclusive OR) of its
670 arguments, which must be plain or long integers. The arguments are
671 converted to a common type.
672 \indexii{bit-wise
}{xor
}
673 \indexii{exclusive
}{or
}
675 The
\code{|
} operator yields the bitwise (inclusive) OR of its
676 arguments, which must be plain or long integers. The arguments are
677 converted to a common type.
678 \indexii{bit-wise
}{or
}
679 \indexii{inclusive
}{or
}
681 \section{Comparisons
\label{comparisons
}}
684 Unlike C, all comparison operations in Python have the same priority,
685 which is lower than that of any arithmetic, shifting or bitwise
686 operation. Also unlike C, expressions like
\code{a < b < c
} have the
687 interpretation that is conventional in mathematics:
688 \indexii{C
}{language
}
691 comparison: or_expr (comp_operator or_expr)*
692 comp_operator: "<"|">"|"=="|">="|"<="|"<>"|"!="|"is"
["not"
]|
["not"
] "in"
695 Comparisons yield integer values:
\code{1} for true,
\code{0} for false.
697 Comparisons can be chained arbitrarily, e.g.,
\code{x < y <= z
} is
698 equivalent to
\code{x < y and y <= z
}, except that
\code{y
} is
699 evaluated only once (but in both cases
\code{z
} is not evaluated at all
700 when
\code{x < y
} is found to be false).
701 \indexii{chaining
}{comparisons
}
703 Formally, if
\var{a
},
\var{b
},
\var{c
},
\ldots,
\var{y
},
\var{z
} are
704 expressions and
\var{opa
},
\var{opb
},
\ldots,
\var{opy
} are comparison
705 operators, then
\var{a opa b opb c
} \ldots \var{y opy z
} is equivalent
706 to
\var{a opa b
} \keyword{and
} \var{b opb c
} \keyword{and
} \ldots
707 \var{y opy z
}, except that each expression is evaluated at most once.
709 Note that
\var{a opa b opb c
} doesn't imply any kind of comparison
710 between
\var{a
} and
\var{c
}, so that, e.g.,
\code{x < y > z
} is
711 perfectly legal (though perhaps not pretty).
713 The forms
\code{<>
} and
\code{!=
} are equivalent; for consistency with
714 C,
\code{!=
} is preferred; where
\code{!=
} is mentioned below
715 \code{<>
} is also accepted. The
\code{<>
} spelling is considered
718 The operators
\code{<
},
\code{>
},
\code{==
},
\code{>=
},
\code{<=
}, and
720 the values of two objects. The objects need not have the same type.
721 If both are numbers, they are coverted to a common type. Otherwise,
722 objects of different types
\emph{always
} compare unequal, and are
723 ordered consistently but arbitrarily.
725 (This unusual definition of comparison was used to simplify the
726 definition of operations like sorting and the
\keyword{in
} and
727 \keyword{not in
} operators. In the future, the comparison rules for
728 objects of different types are likely to change.)
730 Comparison of objects of the same type depends on the type:
735 Numbers are compared arithmetically.
738 Strings are compared lexicographically using the numeric equivalents
739 (the result of the built-in function
\function{ord()
}) of their
740 characters. Unicode and
8-bit strings are fully interoperable in this
744 Tuples and lists are compared lexicographically using comparison of
748 Mappings (dictionaries) are compared through lexicographic
749 comparison of their sorted (key, value) lists.
\footnote{
750 This is expensive since it requires sorting the keys first,
751 but it is about the only sensible definition. An earlier version of
752 Python compared dictionaries by identity only, but this caused
753 surprises because people expected to be able to test a dictionary for
754 emptiness by comparing it to
\code{\
{\
}}.
}
757 Most other types compare unequal unless they are the same object;
758 the choice whether one object is considered smaller or larger than
759 another one is made arbitrarily but consistently within one
760 execution of a program.
764 The operators
\keyword{in
} and
\keyword{not in
} test for set
765 membership.
\code{\var{x
} in
\var{s
}} evaluates to true if
\var{x
}
766 is a member of the set
\var{s
}, and false otherwise.
\code{\var{x
}
767 not in
\var{s
}} returns the negation of
\code{\var{x
} in
\var{s
}}.
768 The set membership test has traditionally been bound to sequences; an
769 object is a member of a set if the set is a sequence and contains an
770 element equal to that object. However, it is possible for an object
771 to support membership tests without being a sequence.
773 For the list and tuple types,
\code{\var{x
} in
\var{y
}} is true if and
774 only if there exists an index
\var{i
} such that
775 \code{\var{x
} ==
\var{y
}[\var{i
}]} is true.
777 For the Unicode and string types,
\code{\var{x
} in
\var{y
}} is true if
778 and only if there exists an index
\var{i
} such that
\code{\var{x
} ==
779 \var{y
}[\var{i
}]} is true. If
\code{\var{x
}} is not a string or
780 Unicode object of length
\code{1}, a
\exception{TypeError
} exception
783 For user-defined classes which define the
\method{__contains__()
} method,
784 \code{\var{x
} in
\var{y
}} is true if and only if
785 \code{\var{y
}.__contains__(
\var{x
})
} is true.
787 For user-defined classes which do not define
\method{__contains__()
} and
788 do define
\method{__getitem__()
},
\code{\var{x
} in
\var{y
}} is true if
789 and only if there is a non-negative integer index
\var{i
} such that
790 \code{\var{x
} ==
\var{y
}[\var{i
}]}, and all lower integer indices
791 do not raise
\exception{IndexError
} exception. (If any other exception
792 is raised, it is as if
\keyword{in
} raised that exception).
794 The operator
\keyword{not in
} is defined to have the inverse true value
798 \indexii{membership
}{test
}
801 The operators
\keyword{is
} and
\keyword{is not
} test for object identity:
802 \code{\var{x
} is
\var{y
}} is true if and only if
\var{x
} and
\var{y
}
803 are the same object.
\code{\var{x
} is not
\var{y
}} yields the inverse
807 \indexii{identity
}{test
}
809 \section{Boolean operations
\label{Booleans
}}
810 \indexii{Boolean
}{operation
}
812 Boolean operations have the lowest priority of all Python operations:
815 expression: or_test | lambda_form
816 or_test: and_test | or_test "or" and_test
817 and_test: not_test | and_test "and" not_test
818 not_test: comparison | "not" not_test
819 lambda_form: "lambda"
[parameter_list
]: expression
822 In the context of Boolean operations, and also when expressions are
823 used by control flow statements, the following values are interpreted
824 as false:
\code{None
}, numeric zero of all types, empty sequences
825 (strings, tuples and lists), and empty mappings (dictionaries). All
826 other values are interpreted as true.
828 The operator
\keyword{not
} yields
\code{1} if its argument is false,
832 The expression
\code{\var{x
} and
\var{y
}} first evaluates
\var{x
}; if
833 \var{x
} is false, its value is returned; otherwise,
\var{y
} is
834 evaluated and the resulting value is returned.
837 The expression
\code{\var{x
} or
\var{y
}} first evaluates
\var{x
}; if
838 \var{x
} is true, its value is returned; otherwise,
\var{y
} is
839 evaluated and the resulting value is returned.
842 (Note that neither
\keyword{and
} nor
\keyword{or
} restrict the value
843 and type they return to
\code{0} and
\code{1}, but rather return the
844 last evaluated argument.
845 This is sometimes useful, e.g., if
\code{s
} is a string that should be
846 replaced by a default value if it is empty, the expression
847 \code{s or 'foo'
} yields the desired value. Because
\keyword{not
} has to
848 invent a value anyway, it does not bother to return a value of the
849 same type as its argument, so e.g.,
\code{not 'foo'
} yields
\code{0},
852 Lambda forms (lambda expressions) have the same syntactic position as
853 expressions. They are a shorthand to create anonymous functions; the
854 expression
\code{lambda
\var{arguments
}:
\var{expression
}}
855 yields a function object that behaves virtually identical to one
863 See section
\ref{function
} for the syntax of parameter lists. Note
864 that functions created with lambda forms cannot contain statements.
866 \indexii{lambda
}{expression
}
867 \indexii{lambda
}{form
}
868 \indexii{anonmymous
}{function
}
870 \strong{Programmer's note:
} Prior to Python
2.1, a lambda form defined
871 inside a function has no access to names defined in the function's
872 namespace. This is because Python had only two scopes: local and
873 global. A common work-around was to use default argument values to
874 pass selected variables into the lambda's namespace, e.g.:
877 def make_incrementor(increment):
878 return lambda x, n=increment: x+n
881 Python
2.1 introduced nested scopes as an optional feature, and this
882 work-around has not been necessary when the feature is enabled. The
883 use of nested scopes is enabled by the statement
\samp{from __future__
884 import nested_scopes
}; future versions of Python will enable nested
885 scopes by default. This version works starting with Python
2.1:
888 from __future__ import nested_scopes
890 def make_incrementor(increment):
891 return lambda x: x+increment
895 \section{Expression lists
\label{exprlists
}}
896 \indexii{expression
}{list
}
899 expression_list: expression ("," expression)*
[","
]
902 An expression list containing at least one comma yields a
903 tuple. The length of the tuple is the number of expressions in the
904 list. The expressions are evaluated from left to right.
907 The trailing comma is required only to create a single tuple (a.k.a. a
908 \emph{singleton
}); it is optional in all other cases. A single
909 expression without a trailing comma doesn't create a
910 tuple, but rather yields the value of that expression.
911 (To create an empty tuple, use an empty pair of parentheses:
913 \indexii{trailing
}{comma
}
916 \section{Summary
\label{summary
}}
918 The following table summarizes the operator
919 precedences
\indexii{operator
}{precedence
} in Python, from lowest
920 precedence (least binding) to highest precedence (most binding).
921 Operators in the same box have the same precedence. Unless the syntax
922 is explicitly given, operators are binary. Operators in the same box
923 group left to right (except for comparisons, which chain from left to
924 right --- see above, and exponentiation, which groups from right to
927 \begin{tableii
}{c|l
}{textrm
}{Operator
}{Description
}
928 \lineii{\keyword{lambda
}} {Lambda expression
}
930 \lineii{\keyword{or
}} {Boolean OR
}
932 \lineii{\keyword{and
}} {Boolean AND
}
934 \lineii{\keyword{not
} \var{x
}} {Boolean NOT
}
936 \lineii{\keyword{in
},
\keyword{not
} \keyword{in
}}{Membership tests
}
937 \lineii{\keyword{is
},
\keyword{is not
}}{Identity tests
}
938 \lineii{\code{<
},
\code{<=
},
\code{>
},
\code{>=
},
939 \code{<>
},
\code{!=
},
\code{==
}}
942 \lineii{\code{|
}} {Bitwise OR
}
944 \lineii{\code{\^
}} {Bitwise XOR
}
946 \lineii{\code{\&
}} {Bitwise AND
}
948 \lineii{\code{<
}\code{<
},
\code{>
}\code{>
}} {Shifts
}
950 \lineii{\code{+
},
\code{-
}}{Addition and subtraction
}
952 \lineii{\code{*
},
\code{/
},
\code{\%
}}
953 {Multiplication, division, remainder
}
955 \lineii{\code{+
\var{x
}},
\code{-
\var{x
}}} {Positive, negative
}
956 \lineii{\code{\~
\var{x
}}} {Bitwise not
}
958 \lineii{\code{**
}} {Exponentiation
}
960 \lineii{\code{\var{x
}.
\var{attribute
}}} {Attribute reference
}
961 \lineii{\code{\var{x
}[\var{index
}]}} {Subscription
}
962 \lineii{\code{\var{x
}[\var{index
}:
\var{index
}]}} {Slicing
}
963 \lineii{\code{\var{f
}(
\var{arguments
}...)
}} {Function call
}
965 \lineii{\code{(
\var{expressions
}\ldots)
}} {Binding or tuple display
}
966 \lineii{\code{[\var{expressions
}\ldots]}} {List display
}
967 \lineii{\code{\
{\var{key
}:
\var{datum
}\ldots\
}}}{Dictionary display
}
968 \lineii{\code{`
\var{expressions
}\ldots`
}} {String conversion
}