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
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
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.
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.
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