Sort list while pushing None values to the end
>>> l = [1, 3, 2, 5, 4, None, 7]
>>> sorted(l, key=lambda x: (x is None, x))
[1, 2, 3, 4, 5, 7, None]
This constructs a tuple for each element in the list, if the value is None
the tuple with be (True, None)
, if the value is anything else it will be (False, x)
(where x
is the value). Since tuples are sorted item by item, this means that all non-None
elements will come first (since False < True
), and then be sorted by value.
Try this:
sorted(l, key=lambda x: float('inf') if x is None else x)
Since infinity is larger than all integers, None
will always be placed last.