Python 2's behavior when comparing objects of different types can be confusing, but it's based on implementation details provided by the language specification.
When comparing objects of different types, Python 2 uses the following order:
To illustrate:
print "100" < "2" # True (lexicographic) print "5" > "9" # False (lexicographic) print "100" < 2 # False (numeric first) print 100 < "2" # True (numeric first, lexicographic second) print 5 > "9" # False (lexicographic) print "5" > 9 # True (numeric first, lexicographic second) print [] > float('inf') # True (non-numeric ordering) print () > [] # True (non-numeric ordering)
This behavior is mandated by the CPython implementation of Python 2. The language spec states that objects of different types are ordered "arbitrarily but consistently," leaving the details up to the implementation.
In Python 3, comparisons between integers and strings raise an error. Other implementations of Python may also have slightly different behavior.
The above is the detailed content of How Does Python 2 Compare Objects of Different Types?. For more information, please follow other related articles on the PHP Chinese website!