anonymous variable

Alex Martelli aleaxit at
Sun Jul 8 04:05:48 EDT 2001

"Vladimir Nesterovsky" <vnestr at> wrote in message
news:9i88o3$hj41s$1 at
> It might be viewed as a "value sort" or "sort by value",
> meaning that a natural sort is done on a list as if each
> its element was represented by some value comparable
> with the "<" operator, produced by a user-specified function:

Right; in addition (which I didn't show in my last post,
but explain in my Cookbook entry at
it's also pretty easy to make it stable (so that items of the
original list that map to the same comparable remain in
the same order as in the original list, a frequent spec:-).

>   def vsort (ls, f):
>     x = map(lambda e,g=f : (g(e),e), ls)
>     x.sort()
>     return map(lambda p:p[1],x)
> and call it
>   alist = vsort(alist, lambda x: x[2])
> This is doing the same thing that your function is doing by a
> different syntax; knowing as little Python as I do I just don't
> know which way's faster. :-)

One should measure times in each specific case, but, roughly,
list comprehensions tend to be a smidgeon faster than map
with a lambda, a smidgeon slower than map when a real
function is already available and needs to be called anyway.

> In Perl they call it Schwartzian transform, but the paradigm's

That's what I thought, too, and I mention it in the Cookbook
entry, but I'm told the Schwartzian Transform is _specifically_
about making it all a one-liner with Perl's grep.  So I coined
the 'decorate=sort=undecorate' (DSU) name for the pattern
in the more-general case; descriptive, if nothing else:-).


More information about the Python-list mailing list