The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Bleepage Open

--

Chapters
00:00 What Is The Logic Behind Order Comparison On Non-Numeric Python Objects
00:34 Answer 1 Score 1
00:52 Accepted Answer Score 3
01:40 Thank you

--

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

--

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