The Python Oracle

What is the logic behind order comparison on non-numeric Python objects

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle3

--

Chapters
00:00 Question
00:45 Accepted answer (Score 3)
01:56 Answer 2 (Score 1)
02:19 Thank you

--

Full question
https://stackoverflow.com/questions/1312...

Accepted answer links:
[docs say]: http://docs.python.org/2/library/stdtype...
[this wart is fixed]: http://docs.python.org/3.0/whatsnew/3.0....

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #implementation

#avk47



ACCEPTED ANSWER

Score 3


In Python2, the docs say:

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.

In Python3, this wart is fixed:

The ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering. Thus, expressions like 1 < '', 0 > None or len <= len are no longer valid, and e.g. None < None raises TypeError instead of returning False. A corollary is that sorting a heterogeneous list no longer makes sense – all the elements must be comparable to each other. Note that this does not apply to the == and != operators: objects of different incomparable types always compare unequal to each other.




ANSWER 2

Score 1


The comparison in such cases is done on the bases of type() of the objects:

for example : type(123) is 'int' and type(list) is 'list', so the string comparison of 'int'<'list' returns to be True

>>> 123<list
True
>>> type(123)<type(list)
True