Sorting a list with entries of unequal types

Steven D'Aprano steve at
Fri Jan 29 02:11:05 CET 2010

On Fri, 29 Jan 2010 11:01:21 +1100, Ben Finney wrote:

> So how should I be sorting a list with entries of “unequal types” such
> that it will work in Python 3?

That depends on how you want the items to be sorted. Python 2.x sorted 
unequal types in some arbitrary but consistent order. If that's all you 
want, then a key function like this will work in Python 3.1:

>>> foo = [1, True, 'green', 4, -27, 15.3]
>>> foo.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() < bool()
>>> foo.sort(key=lambda x: (str(type(x)), x))
>>> foo
[True, 15.3, -27, 1, 4, 'green']

If you want to match the sort order from a specific version of Python, or 
if you want a specific ordering, you'll need to write your own key 


More information about the Python-list mailing list