[Solved] Sort a list where there are strings, floats and integers


Python’s comparison operators wisely refuse to work for variables of incompatible types. Decide on the criterion for sorting your list, encapsulate it in a function and pass it as the key option to sort(). For example, to sort by the repr of each element (a string):

l.sort(key=repr)

To sort by type first, then by the contents:

l.sort(key=lambda x: (str(type(x)), x))

The latter has the advantage that numbers get sorted numerically, strings alphabetically, etc. It will still fail if there are two sublists that cannot be compared, but then you must decide what to do– just extend your key function however you see fit.

2

solved Sort a list where there are strings, floats and integers