I am trying to sort the following mixed list of ints and strings, but getting a TypeError instead. My desired output order is sorted integers then sorted strings.
x=[4,6,9,'ashley','drooks','chay','poo','may']
>>> x.sort()
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
x.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
You can pass a custom key function to
list.sort
:This key function maps each element in the list to a tuple in which the first value is a boolean (
True
for strings andFalse
for numbers) and the second value is the element itself, like this:These tuples are then used to sort the list. Because
False < True
, this makes it so that integers are sorted before strings. Elements with the same boolean value are then sorted by the 2nd value in the tuple.I can see from your comment that you want integers to be sorted first then strings.
So we could sort two separate lists and join them as follows:
Output: