Next: Boolean operations Up: Expressions and conditions Previous: Binary bit-wise operations

Comparisons

Contrary to C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also contrary to C, expressions like a < b < c have the interpretation that is conventional in mathematics:


comparison:     or_expr (comp_operator or_expr)*
comp_operator:  "<"|">"|"=="|">="|"<="|"<>"|"!="|"is" ["not"]|["not"] "in"

Comparisons yield integer values: 1 for true, 0 for false.

Comparisons can be chained arbitrarily, e.g. [tex2html_wrap1146]is equivalent to [tex2html_wrap1148]and [tex2html_wrap1150], except that [tex2html_wrap1152]is evaluated only once (but in both cases [tex2html_wrap1154]is not evaluated at all when [tex2html_wrap1156]is found to be false).

_=8 Formally, [tex2html_wrap1158]is equivalent to [tex2html_wrap1160]and [tex2html_wrap1162]and ... and [tex2html_wrap1164], except that each expression is evaluated at most once.

Note that [tex2html_wrap1166]does not imply any kind of comparison between [tex2html_wrap1168]and [tex2html_wrap1170], e.g. [tex2html_wrap1172]is perfectly legal. _=12

The forms <> and != are equivalent; for consistency with C, != is preferred; where != is mentioned below <> is also implied.

The operators "<", ">", "==", ">=", "<=", and "!=" compare the values of two objects. The objects needn't have the same type. If both are numbers, they are coverted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.

(This unusual definition of comparison is done to simplify the definition of operations like sorting and the in and not in operators.)

Comparison of objects of the same type depends on the type:

The operators in and not in test for sequence membership: if [tex2html_wrap1174]is a sequence, [tex2html_wrap1176]is true if and only if there exists an index [tex2html_wrap1178]such that [tex2html_wrap1180]. [tex2html_wrap1182]yields the inverse truth value. The exception TypeError is raised when [tex2html_wrap1184]is not a sequence, or when [tex2html_wrap1186]is a string and [tex2html_wrap1188]is not a string of length one.

The operators is and is not test for object identity: [tex2html_wrap1190]is true if and only if [tex2html_wrap1192]and [tex2html_wrap1194]are the same object. [tex2html_wrap1196]yields the inverse truth value.



Next: Boolean operations Up: Expressions and conditions Previous: Binary bit-wise operations


guido@cwi.nl