Let's Talk About Lambda Functions!
Carl Banks
imbosol at vt.edu
Fri Jul 26 19:14:01 EDT 2002
Alex Martelli wrote:>
> Paul Rubin wrote:
>
>> "Britt A. Green" <python at experimentzero.org> writes:
>>> So I know what lambda functions are, they're syntax and how they're used.
>>> However I'm not sure *why* one would use a lambda function. What's the
>>> advantage that they offer over a regular function?
>>
>> You can use them inside other expressions, e.g. suppose you want to
>> sort a bunch of strings starting with the second letter:
>>
>> a = ['apple', 'banana', 'pear', 'watermelon']
>> a.sort(lambda x,y: cmp(x[1],y[1]))
>>
>> => ['banana', 'watermelon', 'pear', 'apple']
>>
>> Without lambda, you'd have to define a separate named function:
>
> Without lambda, you might be more tempted to do it right (a la DSU):
>
> aux = [ (x[1], x) for x in a ]
> aux.sort()
> a[:] = [ x for __, x in aux ]
>
> When you're sorting 4 items, it doesn't matter, but try -- not a
> huge number -- just 400, say.
Two things:
First, this has a pitfall: if x is not sortable for some reason, then
the "right" way can throw an exception due to lexical ordering of
tuples. I encountered this when trying to sort classes that didn't
have a __cmp__ method. It seems that a better way is to use id(x) as
the second element and x as the third: (x[1], id(x), x)
Second, if you're going to do it right often, you might want to wrap
it up in a function like this:
def sort_the_right_way (f, a):
aux = [ (f(x), x) for x in a ]
aux.sort()
a[:] = [ x for __, x in aux ]
In which case, the temptation to use lambda returns:
sort_the_right_way (lambda x:x[1], a)
--
CARL BANKS
http://www.aerojockey.com
More information about the Python-list
mailing list