2

I just noticed that Python allows you to compare a string value with a number:

>>> '10' > 1000
True
>>> 'a' > 1000
True
>>> 'a' > -1000
True

Why is any string always greater than any number?

Daniel Reis
  • 12,944
  • 6
  • 43
  • 71
  • 1
    You're comparing two different types that do not have any meaningful comparison, so it is up to the interpreter's implementation, I believe. – Santa Oct 23 '13 at 21:56
  • 2
    If you're asking "Why did Python choose this rule" rather than "What is the rule", [Alex Martelli's answer](http://stackoverflow.com/a/2384139/908494) on a different dup of the question is probably what you're looking for. – abarnert Oct 23 '13 at 21:57
  • @abarnert excellent explanation on the why it came to be so, and why this raises an error in Python 3, thanks. – Daniel Reis Oct 23 '13 at 22:02

1 Answers1

4

In Python 2, §5.3 - Comparisons says:

Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result). Furthermore, some types (for example, file objects) support only a degenerate notion of comparison where any two objects of that type are unequal. Again, such objects are ordered arbitrarily but consistently. The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number.

In Python 3, §4.3 - Comparisons says:

Objects of different types, except different numeric types, never compare equal. Furthermore, some types (for example, function objects) support only a degenerate notion of comparison where any two objects of that type are unequal. The <, <=, > and >= operators will raise a TypeError exception when comparing a complex number with another built-in numeric type, when the objects are of different types that cannot be compared, or in other cases where there is no defined ordering.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • It's probably worth adding the "CPython implementation detail" below that as well, which explains why he sees that particular "consistent but arbitrary" ordering. (Although it isn't 100% complete; it doesn't explain that `None` is always less than anything else, and numeric types are always less than anything non-`None`, or what "numeric" means, or the rules for dealing with pathological subclasses of built-in numeric types, or… But the only place you'll find more explanation is in the source code.) – abarnert Oct 23 '13 at 21:54