Python - Python 2.X and 3.X mixed type comparisons and sorts

Introduction

Python 3.X for non-numeric mixed-type comparisons applies to magnitude tests, not equality.

When sorting, Python 3.X does magnitude testing internally.

In Python 2.X these all work, though mixed types compare by an arbitrary ordering:

c:\python27\python 
>>> 11 == '11'                          # Equality does not convert non-numbers 
False 
>>> 11 >= '11'                          # 2.X compares by type name string: int, str 
False 
>>> ['11', '22'].sort()                 # Ditto for sorts 
>>> [11, '11'].sort() 

Python 3.X does not allow mixed-type magnitude testing, except numeric types and manually converted types:

c:\python33\python 
>>> 11 == '11'                          # 3.X: equality works but magnitude does not 
False 
>>> 11 >= '11' 
TypeError: unorderable types: int() > str() 

>>> ['11', '22'].sort()                 # Ditto for sorts 
>>> [11, '11'].sort() 
TypeError: unorderable types: str() < int() 

>>> 11 > 9.123                          # Mixed numbers convert to highest type 
True 
>>> str(11) >= '11', 11 >= int('11')    # Manual conversions force the issue 
(True, True) 

Related Topic