How do I implement a Schwartzian Transform in Python?


In Perl I sometimes use the Schwartzian Transform to efficiently sort complex arrays:

@sorted = map  { $_->[0] }  # sort by word length
          sort { $a->[1] <=> $b->[1] } # use numeric comparison
          map  { [$_, length($_)] }    # calculate the length of the string

How to implement this transform in Python?

Asked By: planetp



You don’t need to. Python has this feature built in, and in fact Python 3 removed C-style custom comparisons because this is so much better in the vast majority of cases.

To sort by word length:

unsorted.sort(key=lambda item: len(item))

Or, because len is already an unary function:


This also works with the built-in sorted function.

If you want to sort on multiple criteria, you can take advantage of the fact that tuples sort lexicographically:

# sort by word length, then alphabetically in case of a tie
unsorted.sort(key=lambda item: (len(item), item)))
Answered By: Eevee
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.