[Tutor] Debugging a sort error.

Peter Otten __peter__ at web.de
Sun Jan 13 05:59:54 EST 2019


mhysnm1964 at gmail.com wrote:

> Issue, following error is generated after trying to sort a list of
> strings.
> 
> description.sort()
> TypeError: unorderable types: float() < str()

Consider

>>> descriptions = ["foo", "bar", 123, 3.14, 42, 200.1, "0"]
>>> sorted(descriptions)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()

If there are only numbers and strings in the list you can force the sort to 
succeed with the following custom key function:

>>> def key(item):
...     return isinstance(item, str), item
... 

This will move the numbers to the beginning of the list:

>>> sorted(descriptions, key=key)
[3.14, 42, 123, 200.1, '0', 'bar', 'foo']




More information about the Tutor mailing list