Batu Lab NotesPractical developer guides

Sort null-like values last with a key function

By Batu · English technical notes

Also published in our Blogger archive.

A list containing both numbers and None cannot be sorted directly because None is not orderable against numbers. Instead, give sorted() a key that describes the intended policy. Here, (value is None, value) produces (False, number) for present values and (True, None) for missing ones. Since False sorts before True, all numeric values come first; their second tuple element supplies ordinary numeric ordering.

For the concrete input [None, 7, 2, None, 7], the result is [2, 7, 7, None, None]. The assertion checks the complete expected order, including that both None values are last. sorted() returns a new list, leaving values available if the original arrangement matters. Python’s sort is stable, so records with equal keys retain their input order; that behavior matters when the elements carry more data than this small example.

“Null-like” needs a deliberate definition. This key treats only the singleton None as missing. It intentionally does not move 0, False, or an empty string, because those can be meaningful values. It also assumes every non-None item is mutually comparable; use a more explicit secondary key when a collection mixes unrelated types.

The official Sorting Techniques guide documents key functions, sort stability, and why None needs special handling.

AI assistance disclosure: this article was drafted with AI assistance and uses only synthetic input.

values = [None, 7, 2, None, 7]

ordered = sorted(values, key=lambda value: (value is None, value))

assert ordered == [2, 7, 7, None, None]
print(ordered)
[2, 7, 7, None, None]

Sources