Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 odd. Here's the example:

>>> "11" < "2"
True

The strings "11" and "2" are not numbers. They're only characters. It's a common confusion to imagine these values as numbers and hope that "11" comes after "2". If this is...