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
11 \begin{productionlist
}[*
]
12 \production{name
}{\token{othername
}}
15 and no semantics are given, the semantics of this form of
\code{name
}
16 are the same as for
\code{othername
}.
20 \section{Arithmetic conversions
\label{conversions
}}
21 \indexii{arithmetic
}{conversion
}
23 When a description of an arithmetic operator below uses the phrase
24 ``the numeric arguments are converted to a common type,'' the
25 arguments are coerced using the coercion rules listed at the end of
26 chapter
\ref{datamodel
}. If both arguments are standard numeric
27 types, the following coercions are applied:
30 \item If either argument is a complex number, the other is converted
32 \item otherwise, if either argument is a floating point number,
33 the other is converted to floating point;
34 \item otherwise, if either argument is a long integer,
35 the other is converted to long integer;
36 \item otherwise, both must be plain integers and no conversion
40 Some additional rules apply for certain operators (e.g., a string left
41 argument to the `\%' operator). Extensions can define their own
45 \section{Atoms
\label{atoms
}}
48 Atoms are the most basic elements of expressions. The simplest atoms
49 are identifiers or literals. Forms enclosed in
50 reverse quotes or in parentheses, brackets or braces are also
51 categorized syntactically as atoms. The syntax for atoms is:
53 \begin{productionlist
}
55 {\token{identifier
} |
\token{literal
} |
\token{enclosure
}}
56 \production{enclosure
}
57 {\token{parenth_form
} |
\token{list_display
}
58 |
\token{dict_display
} |
\token{string_conversion
}}
62 \subsection{Identifiers (Names)
\label{atom-identifiers
}}
66 An identifier occurring as an atom is a reference to a local, global
67 or built-in name binding. If a name is assigned to anywhere in a code
68 block (even in unreachable code), and is not mentioned in a
69 \keyword{global
} statement in that code block, then it refers to a local
70 name throughout that code block. When it is not assigned to anywhere
71 in the block, or when it is assigned to but also explicitly listed in
72 a
\keyword{global
} statement, it refers to a global name if one exists,
73 else to a built-in name (and this binding may dynamically
74 change).
\footnote{The Python interpreter provides a useful set of
75 predefined built-in functions. It is not recommended to reuse
76 (hide) these names with self defined objects. See the
77 \citetitle[../lib/built-in-funcs.html
]{Python Library Reference
} for
78 the descriptions of built-in functions and methods.
}
79 \indexii{name
}{binding
}
82 \indexii{built-in
}{name
}
83 \indexii{global
}{name
}
85 When the name is bound to an object, evaluation of the atom yields
86 that object. When a name is not bound, an attempt to evaluate it
87 raises a
\exception{NameError
} exception.
90 \strong{Private name mangling:
}%
91 \indexii{name
}{mangling
}%
92 \indexii{private
}{names
}%
93 when an identifier that textually occurs in a class definition begins
94 with two or more underscore characters and does not end in two or more
95 underscores, it is considered a
\dfn{private name
} of that class.
96 Private names are transformed to a longer form before code is
97 generated for them. The transformation inserts the class name in
98 front of the name, with leading underscores removed, and a single
99 underscore inserted in front of the class name. For example, the
100 identifier
\code{__spam
} occurring in a class named
\code{Ham
} will be
101 transformed to
\code{_Ham__spam
}. This transformation is independent
102 of the syntactical context in which the identifier is used. If the
103 transformed name is extremely long (longer than
255 characters),
104 implementation defined truncation may happen. If the class name
105 consists only of underscores, no transformation is done.
108 \subsection{Literals
\label{atom-literals
}}
111 Python supports string literals and various numeric literals:
113 \begin{productionlist
}
115 {\token{stringliteral
} |
\token{integer
}
116 |
\token{longinteger
} |
\token{floatnumber
}
117 |
\token{imagnumber
}}
120 Evaluation of a literal yields an object of the given type (string,
121 integer, long integer, floating point number, complex number) with the
122 given value. The value may be approximated in the case of floating
123 point and imaginary (complex) literals. See section
\ref{literals
}
126 All literals correspond to immutable data types, and hence the
127 object's identity is less important than its value. Multiple
128 evaluations of literals with the same value (either the same
129 occurrence in the program text or a different occurrence) may obtain
130 the same object or a different object with the same value.
131 \indexiii{immutable
}{data
}{type
}
132 \indexii{immutable
}{object
}
135 \subsection{Parenthesized forms
\label{parenthesized
}}
136 \index{parenthesized form
}
138 A parenthesized form is an optional expression list enclosed in
141 \begin{productionlist
}
142 \production{parenth_form
}
143 {"("
[\token{expression_list
}] ")"
}
146 A parenthesized expression list yields whatever that expression list
147 yields: if the list contains at least one comma, it yields a tuple;
148 otherwise, it yields the single expression that makes up the
151 An empty pair of parentheses yields an empty tuple object. Since
152 tuples are immutable, the rules for literals apply (i.e., two
153 occurrences of the empty tuple may or may not yield the same object).
154 \indexii{empty
}{tuple
}
156 Note that tuples are not formed by the parentheses, but rather by use
157 of the comma operator. The exception is the empty tuple, for which
158 parentheses
\emph{are
} required --- allowing unparenthesized ``nothing''
159 in expressions would cause ambiguities and allow common typos to
162 \indexii{tuple
}{display
}
165 \subsection{List displays
\label{lists
}}
166 \indexii{list
}{display
}
167 \indexii{list
}{comprehensions
}
169 A list display is a possibly empty series of expressions enclosed in
172 \begin{productionlist
}
173 \production{list_display
}
174 {"
["
[\token{listmaker
}] "
]"
}
175 \production{listmaker
}
176 {\token{expression
} (
\token{list_for
}
177 | ( ","
\token{expression
})*
[","
] )
}
178 \production{list_iter
}
179 {\token{list_for
} |
\token{list_if
}}
180 \production{list_for
}
181 {"for"
\token{expression_list
} "in"
\token{testlist
}
184 {"if"
\token{test
} [\token{list_iter
}]}
187 A list display yields a new list object. Its contents are specified
188 by providing either a list of expressions or a list comprehension.
189 \indexii{list
}{comprehensions
}
190 When a comma-separated list of expressions is supplied, its elements are
191 evaluated from left to right and placed into the list object in that
192 order. When a list comprehension is supplied, it consists of a
193 single expression followed by at least one
\keyword{for
} clause and zero or
194 more
\keyword{for
} or
\keyword{if
} clauses. In this
195 case, the elements of the new list are those that would be produced
196 by considering each of the
\keyword{for
} or
\keyword{if
} clauses a block,
198 left to right, and evaluating the expression to produce a list element
199 each time the innermost block is reached.
201 \indexii{empty
}{list
}
204 \subsection{Dictionary displays
\label{dict
}}
205 \indexii{dictionary
}{display
}
207 A dictionary display is a possibly empty series of key/datum pairs
208 enclosed in curly braces:
211 \index{key/datum pair
}
213 \begin{productionlist
}
214 \production{dict_display
}
215 {"
{"
[\token{key_datum_list
}] "
}"
}
216 \production{key_datum_list
}
217 {\token{key_datum
} (","
\token{key_datum
})*
[","
]}
218 \production{key_datum
}
219 {\token{expression
} ":"
\token{expression
}}
222 A dictionary display yields a new dictionary object.
225 The key/datum pairs are evaluated from left to right to define the
226 entries of the dictionary: each key object is used as a key into the
227 dictionary to store the corresponding datum.
229 Restrictions on the types of the key values are listed earlier in
230 section
\ref{types
}. (To summarize,the key type should be hashable,
231 which excludes all mutable objects.) Clashes between duplicate keys
232 are not detected; the last datum (textually rightmost in the display)
233 stored for a given key value prevails.
234 \indexii{immutable
}{object
}
237 \subsection{String conversions
\label{string-conversions
}}
238 \indexii{string
}{conversion
}
239 \indexii{reverse
}{quotes
}
240 \indexii{backward
}{quotes
}
243 A string conversion is an expression list enclosed in reverse (a.k.a.
246 \begin{productionlist
}
247 \production{string_conversion
}
248 {"`"
\token{expression_list
} "`"
}
251 A string conversion evaluates the contained expression list and
252 converts the resulting object into a string according to rules
253 specific to its type.
255 If the object is a string, a number,
\code{None
}, or a tuple, list or
256 dictionary containing only objects whose type is one of these, the
257 resulting string is a valid Python expression which can be passed to
258 the built-in function
\function{eval()
} to yield an expression with the
259 same value (or an approximation, if floating point numbers are
262 (In particular, converting a string adds quotes around it and converts
263 ``funny'' characters to escape sequences that are safe to print.)
265 It is illegal to attempt to convert recursive objects (e.g., lists or
266 dictionaries that contain a reference to themselves, directly or
270 The built-in function
\function{repr()
} performs exactly the same
271 conversion in its argument as enclosing it in parentheses and reverse
272 quotes does. The built-in function
\function{str()
} performs a
273 similar but more user-friendly conversion.
278 \section{Primaries
\label{primaries
}}
281 Primaries represent the most tightly bound operations of the language.
284 \begin{productionlist
}
286 {\token{atom
} |
\token{attributeref
}
287 |
\token{subscription
} |
\token{slicing
} |
\token{call
}}
291 \subsection{Attribute references
\label{attribute-references
}}
292 \indexii{attribute
}{reference
}
294 An attribute reference is a primary followed by a period and a name:
296 \begin{productionlist
}
297 \production{attributeref
}
298 {\token{primary
} "."
\token{identifier
}}
301 The primary must evaluate to an object of a type that supports
302 attribute references, e.g., a module, list, or an instance. This
303 object is then asked to produce the attribute whose name is the
304 identifier. If this attribute is not available, the exception
305 \exception{AttributeError
}\exindex{AttributeError
} is raised.
306 Otherwise, the type and value of the object produced is determined by
307 the object. Multiple evaluations of the same attribute reference may
308 yield different objects.
313 \subsection{Subscriptions
\label{subscriptions
}}
316 A subscription selects an item of a sequence (string, tuple or list)
317 or mapping (dictionary) object:
324 \indexii{sequence
}{item
}
326 \begin{productionlist
}
327 \production{subscription
}
328 {\token{primary
} "
["
\token{expression_list
} "
]"
}
331 The primary must evaluate to an object of a sequence or mapping type.
333 If the primary is a mapping, the expression list must evaluate to an
334 object whose value is one of the keys of the mapping, and the
335 subscription selects the value in the mapping that corresponds to that
336 key. (The expression list is a tuple except if it has exactly one
339 If the primary is a sequence, the expression (list) must evaluate to a
340 plain integer. If this value is negative, the length of the sequence
341 is added to it (so that, e.g.,
\code{x
[-
1]} selects the last item of
342 \code{x
}.) The resulting value must be a nonnegative integer less
343 than the number of items in the sequence, and the subscription selects
344 the item whose index is that value (counting from zero).
346 A string's items are characters. A character is not a separate data
347 type but a string of exactly one character.
349 \indexii{string
}{item
}
352 \subsection{Slicings
\label{slicings
}}
356 A slicing selects a range of items in a sequence object (e.g., a
357 string, tuple or list). Slicings may be used as expressions or as
358 targets in assignment or del statements. The syntax for a slicing:
364 \begin{productionlist
}
366 {\token{simple_slicing
} |
\token{extended_slicing
}}
367 \production{simple_slicing
}
368 {\token{primary
} "
["
\token{short_slice
} "
]"
}
369 \production{extended_slicing
}
370 {\token{primary
} "
["
\token{slice_list
} "
]"
}
371 \production{slice_list
}
372 {\token{slice_item
} (","
\token{slice_item
})*
[","
]}
373 \production{slice_item
}
374 {\token{expression
} |
\token{proper_slice
} |
\token{ellipsis
}}
375 \production{proper_slice
}
376 {\token{short_slice
} |
\token{long_slice
}}
377 \production{short_slice
}
378 {[\token{lower_bound
}] ":"
[\token{upper_bound
}]}
379 \production{long_slice
}
380 {\token{short_slice
} ":"
[\token{stride
}]}
381 \production{lower_bound
}
383 \production{upper_bound
}
387 \production{ellipsis
}
391 There is ambiguity in the formal syntax here: anything that looks like
392 an expression list also looks like a slice list, so any subscription
393 can be interpreted as a slicing. Rather than further complicating the
394 syntax, this is disambiguated by defining that in this case the
395 interpretation as a subscription takes priority over the
396 interpretation as a slicing (this is the case if the slice list
397 contains no proper slice nor ellipses). Similarly, when the slice
398 list has exactly one short slice and no trailing comma, the
399 interpretation as a simple slicing takes priority over that as an
400 extended slicing.
\indexii{extended
}{slicing
}
402 The semantics for a simple slicing are as follows. The primary must
403 evaluate to a sequence object. The lower and upper bound expressions,
404 if present, must evaluate to plain integers; defaults are zero and the
405 \code{sys.maxint
}, respectively. If either bound is negative, the
406 sequence's length is added to it. The slicing now selects all items
407 with index
\var{k
} such that
408 \code{\var{i
} <=
\var{k
} <
\var{j
}} where
\var{i
}
409 and
\var{j
} are the specified lower and upper bounds. This may be an
410 empty sequence. It is not an error if
\var{i
} or
\var{j
} lie outside the
411 range of valid indexes (such items don't exist so they aren't
414 The semantics for an extended slicing are as follows. The primary
415 must evaluate to a mapping object, and it is indexed with a key that
416 is constructed from the slice list, as follows. If the slice list
417 contains at least one comma, the key is a tuple containing the
418 conversion of the slice items; otherwise, the conversion of the lone
419 slice item is the key. The conversion of a slice item that is an
420 expression is that expression. The conversion of an ellipsis slice
421 item is the built-in
\code{Ellipsis
} object. The conversion of a
422 proper slice is a slice object (see section
\ref{types
}) whose
423 \member{start
},
\member{stop
} and
\member{step
} attributes are the
424 values of the expressions given as lower bound, upper bound and
425 stride, respectively, substituting
\code{None
} for missing
427 \withsubitem{(slice object attribute)
}{\ttindex{start
}
428 \ttindex{stop
}\ttindex{step
}}
431 \subsection{Calls
\label{calls
}}
434 A call calls a callable object (e.g., a function) with a possibly empty
438 \begin{productionlist
}
440 {\token{primary
} "("
[\token{argument_list
} [","
]] ")"
}
441 \production{argument_list
}
442 {\token{positional_arguments
} [","
\token{keyword_arguments
}]
443 |
\token{keyword_arguments
}}
444 \production{positional_arguments
}
445 {\token{expression
} (","
\token{expression
})*
}
446 \production{keyword_arguments
}
447 {\token{keyword_item
} (","
\token{keyword_item
})*
}
448 \production{keyword_item
}
449 {\token{identifier
} "="
\token{expression
}}
452 A trailing comma may be present after an argument list but does not
453 affect the semantics.
455 The primary must evaluate to a callable object (user-defined
456 functions, built-in functions, methods of built-in objects, class
457 objects, methods of class instances, and certain class instances
458 themselves are callable; extensions may define additional callable
459 object types). All argument expressions are evaluated before the call
460 is attempted. Please refer to section
\ref{function
} for the syntax
461 of formal parameter lists.
463 If keyword arguments are present, they are first converted to
464 positional arguments, as follows. First, a list of unfilled slots is
465 created for the formal parameters. If there are N positional
466 arguments, they are placed in the first N slots. Next, for each
467 keyword argument, the identifier is used to determine the
468 corresponding slot (if the identifier is the same as the first formal
469 parameter name, the first slot is used, and so on). If the slot is
470 already filled, a
\exception{TypeError
} exception is raised.
471 Otherwise, the value of the argument is placed in the slot, filling it
472 (even if the expression is
\code{None
}, it fills the slot). When all
473 arguments have been processed, the slots that are still unfilled are
474 filled with the corresponding default value from the function
475 definition. (Default values are calculated, once, when the function
476 is defined; thus, a mutable object such as a list or dictionary used
477 as default value will be shared by all calls that don't specify an
478 argument value for the corresponding slot; this should usually be
479 avoided.) If there are any unfilled slots for which no default value
480 is specified, a
\exception{TypeError
} exception is raised. Otherwise,
481 the list of filled slots is used as the argument list for the call.
483 If there are more positional arguments than there are formal parameter
484 slots, a
\exception{TypeError
} exception is raised, unless a formal
485 parameter using the syntax
\samp{*identifier
} is present; in this
486 case, that formal parameter receives a tuple containing the excess
487 positional arguments (or an empty tuple if there were no excess
488 positional arguments).
490 If any keyword argument does not correspond to a formal parameter
491 name, a
\exception{TypeError
} exception is raised, unless a formal
492 parameter using the syntax
\samp{**identifier
} is present; in this
493 case, that formal parameter receives a dictionary containing the
494 excess keyword arguments (using the keywords as keys and the argument
495 values as corresponding values), or a (new) empty dictionary if there
496 were no excess keyword arguments.
498 Formal parameters using the syntax
\samp{*identifier
} or
499 \samp{**identifier
} cannot be used as positional argument slots or
500 as keyword argument names. Formal parameters using the syntax
501 \samp{(sublist)
} cannot be used as keyword argument names; the
502 outermost sublist corresponds to a single unnamed argument slot, and
503 the argument value is assigned to the sublist using the usual tuple
504 assignment rules after all other parameter processing is done.
506 A call always returns some value, possibly
\code{None
}, unless it
507 raises an exception. How this value is computed depends on the type
508 of the callable object.
514 \item[a user-defined function:
] The code block for the function is
515 executed, passing it the argument list. The first thing the code
516 block will do is bind the formal parameters to the arguments; this is
517 described in section
\ref{function
}. When the code block executes a
518 \keyword{return
} statement, this specifies the return value of the
520 \indexii{function
}{call
}
521 \indexiii{user-defined
}{function
}{call
}
522 \obindex{user-defined function
}
525 \item[a built-in function or method:
] The result is up to the
526 interpreter; see the
\citetitle[../lib/built-in-funcs.html
]{Python
527 Library Reference
} for the descriptions of built-in functions and
529 \indexii{function
}{call
}
530 \indexii{built-in function
}{call
}
531 \indexii{method
}{call
}
532 \indexii{built-in method
}{call
}
533 \obindex{built-in method
}
534 \obindex{built-in function
}
538 \item[a class object:
] A new instance of that class is returned.
540 \indexii{class object
}{call
}
542 \item[a class instance method:
] The corresponding user-defined
543 function is called, with an argument list that is one longer than the
544 argument list of the call: the instance becomes the first argument.
545 \obindex{class instance
}
547 \indexii{class instance
}{call
}
549 \item[a class instance:
] The class must define a
\method{__call__()
}
550 method; the effect is then the same as if that method was called.
551 \indexii{instance
}{call
}
552 \withsubitem{(object method)
}{\ttindex{__call__()
}}
557 \section{The power operator
\label{power
}}
559 The power operator binds more tightly than unary operators on its
560 left; it binds less tightly than unary operators on its right. The
563 \begin{productionlist
}
565 {\token{primary
} ["**"
\token{u_expr
}]}
568 Thus, in an unparenthesized sequence of power and unary operators, the
569 operators are evaluated from right to left (this does not constrain
570 the evaluation order for the operands).
572 The power operator has the same semantics as the built-in
573 \function{pow()
} function, when called with two arguments: it yields
574 its left argument raised to the power of its right argument. The
575 numeric arguments are first converted to a common type. The result
576 type is that of the arguments after coercion; if the result is not
577 expressible in that type (as in raising an integer to a negative
578 power, or a negative floating point number to a broken power), a
579 \exception{TypeError
} exception is raised.
582 \section{Unary arithmetic operations
\label{unary
}}
583 \indexiii{unary
}{arithmetic
}{operation
}
584 \indexiii{unary
}{bit-wise
}{operation
}
586 All unary arithmetic (and bit-wise) operations have the same priority:
588 \begin{productionlist
}
590 {\token{power
} | "-"
\token{u_expr
}
591 | "+"
\token{u_expr
} | "~"
\token{u_expr
}}
594 The unary
\code{-
} (minus) operator yields the negation of its
599 The unary
\code{+
} (plus) operator yields its numeric argument
603 The unary
\code{\~
} (invert) operator yields the bit-wise inversion
604 of its plain or long integer argument. The bit-wise inversion of
605 \code{x
} is defined as
\code{-(x+
1)
}. It only applies to integral
609 In all three cases, if the argument does not have the proper type,
610 a
\exception{TypeError
} exception is raised.
614 \section{Binary arithmetic operations
\label{binary
}}
615 \indexiii{binary
}{arithmetic
}{operation
}
617 The binary arithmetic operations have the conventional priority
618 levels. Note that some of these operations also apply to certain
619 non-numeric types. Apart from the power operator, there are only two
620 levels, one for multiplicative operators and one for additive
623 \begin{productionlist
}
625 {\token{u_expr
} |
\token{m_expr
} "*"
\token{u_expr
}
626 |
\token{m_expr
} "/"
\token{u_expr
}
627 |
\token{m_expr
} "\%"
\token{u_expr
}}
629 {\token{m_expr
} |
\token{aexpr
} "+"
\token{m_expr
}
630 \token{aexpr
} "-"
\token{m_expr
}}
633 The
\code{*
} (multiplication) operator yields the product of its
634 arguments. The arguments must either both be numbers, or one argument
635 must be an integer (plain or long) and the other must be a sequence.
636 In the former case, the numbers are converted to a common type and
637 then multiplied together. In the latter case, sequence repetition is
638 performed; a negative repetition factor yields an empty sequence.
639 \index{multiplication
}
641 The
\code{/
} (division) operator yields the quotient of its
642 arguments. The numeric arguments are first converted to a common
643 type. Plain or long integer division yields an integer of the same
644 type; the result is that of mathematical division with the `floor'
645 function applied to the result. Division by zero raises the
646 \exception{ZeroDivisionError
} exception.
647 \exindex{ZeroDivisionError
}
650 The
\code{\%
} (modulo) operator yields the remainder from the
651 division of the first argument by the second. The numeric arguments
652 are first converted to a common type. A zero right argument raises
653 the
\exception{ZeroDivisionError
} exception. The arguments may be floating
654 point numbers, e.g.,
\code{3.14\%
0.7} equals
\code{0.34} (since
655 \code{3.14} equals
\code{4*
0.7 +
0.34}.) The modulo operator always
656 yields a result with the same sign as its second operand (or zero);
657 the absolute value of the result is strictly smaller than the second
661 The integer division and modulo operators are connected by the
662 following identity:
\code{x == (x/y)*y + (x\%y)
}. Integer division and
663 modulo are also connected with the built-in function
\function{divmod()
}:
664 \code{divmod(x, y) == (x/y, x\%y)
}. These identities don't hold for
665 floating point and complex numbers; there similar identities hold
666 approximately where
\code{x/y
} is replaced by
\code{floor(x/y)
}) or
667 \code{floor(x/y) -
1} (for floats),
\footnote{
668 If x is very close to an exact integer multiple of y, it's
669 possible for
\code{floor(x/y)
} to be one larger than
670 \code{(x-x\%y)/y
} due to rounding. In such cases, Python returns
671 the latter result, in order to preserve that
\code{divmod(x,y)
[0]
672 * y + x \%
{} y
} be very close to
\code{x
}.
673 } or
\code{floor((x/y).real)
} (for
676 The
\code{+
} (addition) operator yields the sum of its arguments.
677 The arguments must either both be numbers or both sequences of the
678 same type. In the former case, the numbers are converted to a common
679 type and then added together. In the latter case, the sequences are
683 The
\code{-
} (subtraction) operator yields the difference of its
684 arguments. The numeric arguments are first converted to a common
689 \section{Shifting operations
\label{shifting
}}
690 \indexii{shifting
}{operation
}
692 The shifting operations have lower priority than the arithmetic
695 \begin{productionlist
}
696 \production{shift_expr
}
698 |
\token{shift_expr
} ( "<<" | ">>" )
\token{a_expr
}}
701 These operators accept plain or long integers as arguments. The
702 arguments are converted to a common type. They shift the first
703 argument to the left or right by the number of bits given by the
706 A right shift by
\var{n
} bits is defined as division by
707 \code{pow(
2,
\var{n
})
}. A left shift by
\var{n
} bits is defined as
708 multiplication with
\code{pow(
2,
\var{n
})
}; for plain integers there is
709 no overflow check so in that case the operation drops bits and flips
710 the sign if the result is not less than
\code{pow(
2,
31)
} in absolute
711 value. Negative shift counts raise a
\exception{ValueError
}
716 \section{Binary bit-wise operations
\label{bitwise
}}
717 \indexiii{binary
}{bit-wise
}{operation
}
719 Each of the three bitwise operations has a different priority level:
721 \begin{productionlist
}
722 \production{and_expr
}
723 {\token{shift_expr
} |
\token{and_expr
} "\&"
\token{shift_expr
}}
724 \production{xor_expr
}
725 {\token{and_expr
} |
\token{xor_expr
} "
\textasciicircum"
\token{and_expr
}}
727 {\token{xor_expr
} |
\token{or_expr
} "|"
\token{xor_expr
}}
730 The
\code{\&
} operator yields the bitwise AND of its arguments, which
731 must be plain or long integers. The arguments are converted to a
733 \indexii{bit-wise
}{and
}
735 The
\code{\^
} operator yields the bitwise XOR (exclusive OR) of its
736 arguments, which must be plain or long integers. The arguments are
737 converted to a common type.
738 \indexii{bit-wise
}{xor
}
739 \indexii{exclusive
}{or
}
741 The
\code{|
} operator yields the bitwise (inclusive) OR of its
742 arguments, which must be plain or long integers. The arguments are
743 converted to a common type.
744 \indexii{bit-wise
}{or
}
745 \indexii{inclusive
}{or
}
748 \section{Comparisons
\label{comparisons
}}
751 Unlike C, all comparison operations in Python have the same priority,
752 which is lower than that of any arithmetic, shifting or bitwise
753 operation. Also unlike C, expressions like
\code{a < b < c
} have the
754 interpretation that is conventional in mathematics:
755 \indexii{C
}{language
}
757 \begin{productionlist
}
758 \production{comparison
}
759 {\token{or_expr
} (
\token{comp_operator
} \token{or_expr
} )*
}
760 \production{comp_operator
}
761 {"<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
762 | "is"
["not"
] |
["not"
] "in"
}
765 Comparisons yield integer values:
\code{1} for true,
\code{0} for false.
767 Comparisons can be chained arbitrarily, e.g.,
\code{x < y <= z
} is
768 equivalent to
\code{x < y and y <= z
}, except that
\code{y
} is
769 evaluated only once (but in both cases
\code{z
} is not evaluated at all
770 when
\code{x < y
} is found to be false).
771 \indexii{chaining
}{comparisons
}
773 Formally, if
\var{a
},
\var{b
},
\var{c
},
\ldots,
\var{y
},
\var{z
} are
774 expressions and
\var{opa
},
\var{opb
},
\ldots,
\var{opy
} are comparison
775 operators, then
\var{a opa b opb c
} \ldots \var{y opy z
} is equivalent
776 to
\var{a opa b
} \keyword{and
} \var{b opb c
} \keyword{and
} \ldots
777 \var{y opy z
}, except that each expression is evaluated at most once.
779 Note that
\var{a opa b opb c
} doesn't imply any kind of comparison
780 between
\var{a
} and
\var{c
}, so that, e.g.,
\code{x < y > z
} is
781 perfectly legal (though perhaps not pretty).
783 The forms
\code{<>
} and
\code{!=
} are equivalent; for consistency with
784 C,
\code{!=
} is preferred; where
\code{!=
} is mentioned below
785 \code{<>
} is also accepted. The
\code{<>
} spelling is considered
788 The operators
\code{<
},
\code{>
},
\code{==
},
\code{>=
},
\code{<=
}, and
790 the values of two objects. The objects need not have the same type.
791 If both are numbers, they are coverted to a common type. Otherwise,
792 objects of different types
\emph{always
} compare unequal, and are
793 ordered consistently but arbitrarily.
795 (This unusual definition of comparison was used to simplify the
796 definition of operations like sorting and the
\keyword{in
} and
797 \keyword{not in
} operators. In the future, the comparison rules for
798 objects of different types are likely to change.)
800 Comparison of objects of the same type depends on the type:
805 Numbers are compared arithmetically.
808 Strings are compared lexicographically using the numeric equivalents
809 (the result of the built-in function
\function{ord()
}) of their
810 characters. Unicode and
8-bit strings are fully interoperable in this
814 Tuples and lists are compared lexicographically using comparison of
818 Mappings (dictionaries) are compared through lexicographic
819 comparison of their sorted (key, value) lists.
\footnote{
820 This is expensive since it requires sorting the keys first,
821 but it is about the only sensible definition. An earlier version of
822 Python compared dictionaries by identity only, but this caused
823 surprises because people expected to be able to test a dictionary for
824 emptiness by comparing it to
\code{\
{\
}}.
}
827 Most other types compare unequal unless they are the same object;
828 the choice whether one object is considered smaller or larger than
829 another one is made arbitrarily but consistently within one
830 execution of a program.
834 The operators
\keyword{in
} and
\keyword{not in
} test for set
835 membership.
\code{\var{x
} in
\var{s
}} evaluates to true if
\var{x
}
836 is a member of the set
\var{s
}, and false otherwise.
\code{\var{x
}
837 not in
\var{s
}} returns the negation of
\code{\var{x
} in
\var{s
}}.
838 The set membership test has traditionally been bound to sequences; an
839 object is a member of a set if the set is a sequence and contains an
840 element equal to that object. However, it is possible for an object
841 to support membership tests without being a sequence. In particular,
842 dictionaries support memership testing as a nicer way of spelling
843 \code{\var{key
} in
\var{dict
}}; other mapping types may follow suit.
845 For the list and tuple types,
\code{\var{x
} in
\var{y
}} is true if and
846 only if there exists an index
\var{i
} such that
847 \code{\var{x
} ==
\var{y
}[\var{i
}]} is true.
849 For the Unicode and string types,
\code{\var{x
} in
\var{y
}} is true if
850 and only if there exists an index
\var{i
} such that
\code{\var{x
} ==
851 \var{y
}[\var{i
}]} is true. If
\code{\var{x
}} is not a string or
852 Unicode object of length
\code{1}, a
\exception{TypeError
} exception
855 For user-defined classes which define the
\method{__contains__()
} method,
856 \code{\var{x
} in
\var{y
}} is true if and only if
857 \code{\var{y
}.__contains__(
\var{x
})
} is true.
859 For user-defined classes which do not define
\method{__contains__()
} and
860 do define
\method{__getitem__()
},
\code{\var{x
} in
\var{y
}} is true if
861 and only if there is a non-negative integer index
\var{i
} such that
862 \code{\var{x
} ==
\var{y
}[\var{i
}]}, and all lower integer indices
863 do not raise
\exception{IndexError
} exception. (If any other exception
864 is raised, it is as if
\keyword{in
} raised that exception).
866 The operator
\keyword{not in
} is defined to have the inverse true value
870 \indexii{membership
}{test
}
873 The operators
\keyword{is
} and
\keyword{is not
} test for object identity:
874 \code{\var{x
} is
\var{y
}} is true if and only if
\var{x
} and
\var{y
}
875 are the same object.
\code{\var{x
} is not
\var{y
}} yields the inverse
879 \indexii{identity
}{test
}
882 \section{Boolean operations
\label{Booleans
}}
883 \indexii{Boolean
}{operation
}
885 Boolean operations have the lowest priority of all Python operations:
887 \begin{productionlist
}
888 \production{expression
}
889 {\token{or_test
} |
\token{lambda_form
}}
891 {\token{and_test
} |
\token{or_test
} "or"
\token{and_test
}}
892 \production{and_test
}
893 {\token{not_test
} |
\token{and_test
} "and"
\token{not_test
}}
894 \production{not_test
}
895 {\token{comparison
} | "not"
\token{not_test
}}
896 \production{lambda_form
}
897 {"lambda"
[\token{parameter_list
}]:
\token{expression
}}
900 In the context of Boolean operations, and also when expressions are
901 used by control flow statements, the following values are interpreted
902 as false:
\code{None
}, numeric zero of all types, empty sequences
903 (strings, tuples and lists), and empty mappings (dictionaries). All
904 other values are interpreted as true.
906 The operator
\keyword{not
} yields
\code{1} if its argument is false,
910 The expression
\code{\var{x
} and
\var{y
}} first evaluates
\var{x
}; if
911 \var{x
} is false, its value is returned; otherwise,
\var{y
} is
912 evaluated and the resulting value is returned.
915 The expression
\code{\var{x
} or
\var{y
}} first evaluates
\var{x
}; if
916 \var{x
} is true, its value is returned; otherwise,
\var{y
} is
917 evaluated and the resulting value is returned.
920 (Note that neither
\keyword{and
} nor
\keyword{or
} restrict the value
921 and type they return to
\code{0} and
\code{1}, but rather return the
922 last evaluated argument.
923 This is sometimes useful, e.g., if
\code{s
} is a string that should be
924 replaced by a default value if it is empty, the expression
925 \code{s or 'foo'
} yields the desired value. Because
\keyword{not
} has to
926 invent a value anyway, it does not bother to return a value of the
927 same type as its argument, so e.g.,
\code{not 'foo'
} yields
\code{0},
930 Lambda forms (lambda expressions) have the same syntactic position as
931 expressions. They are a shorthand to create anonymous functions; the
932 expression
\code{lambda
\var{arguments
}:
\var{expression
}}
933 yields a function object that behaves virtually identical to one
941 See section
\ref{function
} for the syntax of parameter lists. Note
942 that functions created with lambda forms cannot contain statements.
944 \indexii{lambda
}{expression
}
945 \indexii{lambda
}{form
}
946 \indexii{anonmymous
}{function
}
948 \strong{Programmer's note:
} Prior to Python
2.1, a lambda form defined
949 inside a function has no access to names defined in the function's
950 namespace. This is because Python had only two scopes: local and
951 global. A common work-around was to use default argument values to
952 pass selected variables into the lambda's namespace, e.g.:
955 def make_incrementor(increment):
956 return lambda x, n=increment: x+n
959 As of Python
2.1, nested scopes were introduced, and this work-around
960 has not been necessary. Python
2.1 supports nested scopes in modules
961 which include the statement
\samp{from __future__ import
962 nested_scopes
}, and more recent versions of Python enable nested
963 scopes by default. This version works starting with Python
2.1:
966 from __future__ import nested_scopes
968 def make_incrementor(increment):
969 return lambda x: x+increment
973 \section{Expression lists
\label{exprlists
}}
974 \indexii{expression
}{list
}
976 \begin{productionlist
}
977 \production{expression_list
}
978 {\token{expression
} ( ","
\token{expression
} )*
[","
]}
981 An expression list containing at least one comma yields a
982 tuple. The length of the tuple is the number of expressions in the
983 list. The expressions are evaluated from left to right.
986 The trailing comma is required only to create a single tuple (a.k.a. a
987 \emph{singleton
}); it is optional in all other cases. A single
988 expression without a trailing comma doesn't create a
989 tuple, but rather yields the value of that expression.
990 (To create an empty tuple, use an empty pair of parentheses:
992 \indexii{trailing
}{comma
}
995 \section{Summary
\label{summary
}}
997 The following table summarizes the operator
998 precedences
\indexii{operator
}{precedence
} in Python, from lowest
999 precedence (least binding) to highest precedence (most binding).
1000 Operators in the same box have the same precedence. Unless the syntax
1001 is explicitly given, operators are binary. Operators in the same box
1002 group left to right (except for comparisons, which chain from left to
1003 right --- see above, and exponentiation, which groups from right to
1006 \begin{tableii
}{c|l
}{textrm
}{Operator
}{Description
}
1007 \lineii{\keyword{lambda
}} {Lambda expression
}
1009 \lineii{\keyword{or
}} {Boolean OR
}
1011 \lineii{\keyword{and
}} {Boolean AND
}
1013 \lineii{\keyword{not
} \var{x
}} {Boolean NOT
}
1015 \lineii{\keyword{in
},
\keyword{not
} \keyword{in
}}{Membership tests
}
1016 \lineii{\keyword{is
},
\keyword{is not
}}{Identity tests
}
1017 \lineii{\code{<
},
\code{<=
},
\code{>
},
\code{>=
},
1018 \code{<>
},
\code{!=
},
\code{==
}}
1021 \lineii{\code{|
}} {Bitwise OR
}
1023 \lineii{\code{\^
}} {Bitwise XOR
}
1025 \lineii{\code{\&
}} {Bitwise AND
}
1027 \lineii{\code{<
}\code{<
},
\code{>
}\code{>
}} {Shifts
}
1029 \lineii{\code{+
},
\code{-
}}{Addition and subtraction
}
1031 \lineii{\code{*
},
\code{/
},
\code{\%
}}
1032 {Multiplication, division, remainder
}
1034 \lineii{\code{+
\var{x
}},
\code{-
\var{x
}}} {Positive, negative
}
1035 \lineii{\code{\~
\var{x
}}} {Bitwise not
}
1037 \lineii{\code{**
}} {Exponentiation
}
1039 \lineii{\code{\var{x
}.
\var{attribute
}}} {Attribute reference
}
1040 \lineii{\code{\var{x
}[\var{index
}]}} {Subscription
}
1041 \lineii{\code{\var{x
}[\var{index
}:
\var{index
}]}} {Slicing
}
1042 \lineii{\code{\var{f
}(
\var{arguments
}...)
}} {Function call
}
1044 \lineii{\code{(
\var{expressions
}\ldots)
}} {Binding or tuple display
}
1045 \lineii{\code{[\var{expressions
}\ldots]}} {List display
}
1046 \lineii{\code{\
{\var{key
}:
\var{datum
}\ldots\
}}}{Dictionary display
}
1047 \lineii{\code{`
\var{expressions
}\ldots`
}} {String conversion
}