Silveris Silveris - 8 months ago 28
Python Question

Sort a list where there are strings, floats and integers

I need some help because I wanted to know if there is a way in Python to sort a list where there are strings, floats and integers in it.

I tried to use list.sort() method but of course it did not work.

Here is an example of a list I would like to sort :

l = [1, 2.0, "titi", True, [2, 3, 4, [3, [3, 4]], 5]]

I would like it to be sorted by value by floats and ints, and then by type : floats and ints first, then strings, then booleans and then lists. I would like to use Python 2.7 but I am not allowed to..


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):


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.