5.9 Comparisons


comparison:     or_expr (comp_operator or_expr)*

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


Formally, if a, b, c, ..., y, z are expressions and opa, opb, ..., opy are comparison operators, then a opa b opb c ...y opy z is equivalent to a opa b and b opb c and ... y opy z, except that each expression is evaluated at most once.

Note that a opa b opb c doesn't imply any kind of comparison between a and c, so that, e.g., x < y > z is perfectly legal (though perhaps not pretty).


The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not 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.


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

The operators in and not in test for set membership. x in s evaluates to true if x is a member of the set s, and false otherwise. x not in s returns the negation of x in s. The set membership test has traditionally been bound to sequences; an object is a member of a set if the set is a sequence and contains an element equal to that object. However, it is possible for an object to support membership tests without being a sequence.

For the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true.

For the Unicode and string types, x in y is true if and only if there exists an index i such that x == y[i] is true. If x is not a string or Unicode object of length 1, a TypeError exception is raised.


For user-defined classes which do not define __contains__() and do define __getitem__(), x in y is true if and only if there is a non-negative integer index i such that x == y[i], and all lower integer indices do not raise IndexError exception. (If any other exception is raised, it is as if in raised that exception).




... lists.5.3
This is expensive since it requires sorting the keys first, but it is about the only sensible definition. An earlier version of Python compared dictionaries by identity only, but this caused surprises because people expected to be able to test a dictionary for emptiness by comparing it to {}.