2

So this has been bothering me and I haven't been able to find anything online about it. Could someone please explain this behavior in python? Why does it return True rather than throwing an exception? Thanks

In [1]: 1 < [1, 2, 3]
Out[1]: True
ast4
  • 791
  • 8
  • 19
  • Here's a small bit of information on this behavior (last paragraph): http://docs.python.org/2.7/tutorial/datastructures.html#comparing-sequences-and-other-types – flornquake Sep 04 '13 at 19:12

3 Answers3

10

It does throw an exception-- these days, anyway:

$ python3
Python 3.3.0 (default, Apr 17 2013, 13:40:43) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 < [1,2,3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < list()

Python used to let comparisons pass like this in the old days because it was sometimes handy to be able to sort everything automatically in heterogeneous containers, but that led to more bugs than it did convenience, and so it was fixed in Python 3.

DSM
  • 342,061
  • 65
  • 592
  • 494
  • -1 for pretending that Python 2 is obsolete or rare. – Marcin Sep 04 '13 at 19:11
  • 3
    @Marcin: I spend most of my work days (including right now, actually) writing in Python 2.7, so I'm not sure how I could think it's obsolete, or why I would say that. However, it's definitely true that it's not the leading edge of Python development, and there have been many years of development now on Python 3, with 3.4 in the works, so I think "old days" is justified. Anyway, there are [other people](http://stackoverflow.com/users/241039/oleh-prypin) who downvote using exactly the opposite criterion, so I suppose it all balances out in the end! – DSM Sep 04 '13 at 19:27
4

It was an attempt to make sorting easier. Python tries to make objects with no meaningful comparison operation compare in a consistent but arbitrary order. In Python 3, they changed it; this would be a TypeError in Python 3.

user2357112
  • 260,549
  • 28
  • 431
  • 505
4

If I recall correctly, the behavior you're seeing in py2 is actually comparing the types.

>>> 1 < [1,2,3]
True
>>> 1 > [1,2,3]
False
>>> int < list
True
>>> int > list
False

As I delve further, I think it compares the names of the types, although perhaps somewhat indirectly, maybe through one of these although I can't tell:

>>> repr(int)
"<type 'int'>"
>>> int.__name__
'int'
>>> repr(list)
"<type 'list'>"
>>> list.__name__
'list'

>>> 'int' < 'list'
True
>>> "<type 'int'>" < "<type 'list'>"
True
Brian
  • 3,091
  • 16
  • 29