Python sorting by multiple criteria

List the three criteria in your key:

sorted(inputlist, key=lambda e: (len(e[0]), e[0], e[1]))

Now you are sorting each element first by the length, then by comparing the first element directly (which in only used when the first element is of equal length), then by the value of the last integer.

Python sorts tuples and lists like these lexicographically; compare the first element, and only if that doesn’t differ, compare the second element, etc.

The second element here is e[0] which will only be used if both compared entries have nested lists of equal length. These are again compared lexicographically, so pairing up elements until a pair differs.

Leave a Comment