Comparison operators
In Chapter 2, Simple Data Types, we looked at the six essential comparison operators: <
, >
, ==
, !=
, <=
, and >=
. The minimum of ==
and !=
are defined by default for all classes, so that we can always compare objects for simple equality. For the numeric types, the ordering operators are also defined. Furthermore, Python's type coercion rules are implemented by the numeric types so that the expression 2 < 3.0
will have the int
coerced to float
.
For sequences, including str
, bytes
, tuple
, and list
, the two operands are compared item-by-item. This tends to put strings into alphabetical order. This works well for words. It also usually puts tuples into the expected order. However, for number-like strings, the sorting may seem a little ...
Get Python Essentials now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.