The operators <, >, <=, >=, == and != compare the values of two objects.

The default behavior for equality comparison (== and !=) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive. The behavior of the default equality comparison, that instances with different identities are always unequal.

Numbers of built in Numeric Type (int, float, complex) and fractions.Fraction and decimal.Decimal can be compared within and across their type, with the restriction that complex numbers do not support order comparison. Within the limits of the types involved, they compare algorithmically correct without loss of precision.

Strings compare lexicographically using the numerical Unicode code points (the result of the built-in function ord( ) ) of their characters. Strings and binary sequences cannot be directly compared.

Sequences (list, tuple or range) can be compared within each of their types, with the restriction that ranges do not support order comparison. Sequences compare lexicographically using the comparison of corresponding elements, whereby reflexivity of the elements is enforced.

**Lexicographical comparison between built-in collections works as follows:**

- For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal.

Example:

>>> [1,2] == (1,2)

False

because the type is not the same. - Collections that support order comparison are ordered the same as their first unequal elements. If a corresponding element does not exist, the shorter collection is ordered first (for example, [1,2] <= [1,2,3] is true).
- Mappings ( an instance of dict) compare equal if and only if they have equal (key, value) pairs. Equality comparison of the keys and values enforces reflexivity.
- The comparison should be symmetric. In other words, the following expressions should have the same result:

```
x == y and y == x
x != y and y != x
x < y and y > x
x <= y and y >= x
```

- The comparison should be transitive.

```
x > y and y > z implies x > z
x < y and y <= z implies x < z
```

## Leave a Reply