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.
x < y < = z is
equivalent to x < y and
y < = z, except that y is
evaluated only once (but in both cases z is not evaluated at all
when x < y is found to be false).
Formally,
e0op1e1op2e2...en-1opnen is equivalent to
e0op1e1 and
e1op2e2 and
... and
en-1opnen, except that each expression is evaluated at most once.
Note that e0op1e1op2e2 does not imply any kind of comparison between e0 and e2, e.g. x < y > z is perfectly legal.
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:
ord
) of their characters.
The operators in
and not in
test for sequence
membership: if y is a sequence,
x in
y is true if and
only if there exists an index i such that x = y[i].
x not in
y yields the inverse truth value. The exception
TypeError
is raised when y is not a sequence, or when y is
a string and x is not a string of length one.5.2
The operators is
and is not
test for object identity:
x is
y is true if and only if x and y are the same
object.
x is not
y yields the inverse truth value.