The built-in function sorted
and sequence method sort
require that the elements in the sequence be of types that can be compared: they will fail, for example, if a list contains a mixture of strings and numbers. However, it is frequently the case that a list contains numbers and the special value, None
(perhaps denoting missing data). Devise a way to sort such a list by passing a lambda
function in the argument key
; the None
values should end up at the end of the sorted list.
One solution is to construct a tuple with two elements for each item in the list to be sorted: first, a boolean value indicating whether the item is None
or not; second, the value itself. When these tuples are sorted, the first element is False
for all the numbers (which can be compared as the second element) and True
for all the None
values. Since False
always compares as "less than" True
, there is no need to compare different types:
>>> lst = [4, 2, 6, None, 0, 8, None, 3]
>>> lst.sort(key=lambda e: (e is None, e))
>>> lst
[0, 2, 3, 4, 6, 8, None, None]