Skip to content
Quantoros

I want to do a complicated sort: can you do a Schwartzian Transform in Python?

PythonLevel: Intermediate

I want to do a complicated sort: can you do a Schwartzian Transform in Python?

Hints
  • Identify object types, mutability and execution order.
  • Trace a minimal example: which values and references change?

Answer

The technique, attributed to Randal Schwartz of the Perl community, sorts the elements of a list by a metric which maps each element to its “sort value”. In Python, use the key argument for the list.sort() method:

Isorted = L[:]
Isorted.sort(key=lambda s: int(s[10:15]))

Source and licence: Python 3.14.0 Programming FAQ — Python Software Foundation · PSF-2.0

Related questions