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]]
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.