views:

126

answers:

2

The following snippet is annotated with the output (as seen on ideone.com):

print "100" < "2"      # True
print "5" > "9"        # False

print "100" < 2        # False
print 100 < "2"        # True

print 5 > "9"          # False
print "5" > 9          # True

Can someone explain why the output is as such?


Implementation details

  • Is this behavior mandated by the language spec, or is it up to implementors?
  • Are there differences between any of the major Python implementations?
  • Are there differences between versions of the Python language?
+4  A: 

Strings are compared lexicographically, and dissimilar types are compared by the name of their type ("int" < "string"). 3.x fixes the second point by making them non-comparable.

Ignacio Vazquez-Abrams
+11  A: 

From the manual:

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

When you order two strings or two numeric types the ordering is done in the expected way (lexicographic ordering for string, numeric ordering for integers).

When you order a string and an integer the type names are ordered. "str" is lexicographically after "int", "float", "long", "list", "bool", etc. However a tuple will order higher than a string because "tuple" > "str":

0 > 'foo'
False
[1, 2] > 'foo'
False
(1, 2) > 'foo'
True

  • Is this behavior mandated by the language spec, or is it up to implementors?

There is no language specification. The language reference says:

Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.

So it is an implementation detail.

  • Are there differences between any of the major Python implementations?

I can't answer this one because I have only used the official CPython implementation, but there are other implementations of Python such as PyPy.

  • Are there differences between versions of the Python language?

In Python 3.x the behaviour has been changed so that attempting to order an integer and a string will raise an error:

>>> '10' > 5
Traceback (most recent call last):
  File "", line 1, in 
    '10' > 5
TypeError: unorderable types: str() > int()
Mark Byers
That's good that they changed it in Py3k. When I first saw this question, my thoughts were 'what, this doesn't raise an error?'.
Alex JL
N.B. An exception to the 2.x rule that different types are ordered by the name of the type is that the None object always compares as less than every other type.In 3.x comparing None with another type will still raise a TypeError.
Dave Kirby