Let's Talk About Lambda Functions!

Paul Rubin phr-n2002b at NOSPAMnightsong.com
Fri Jul 26 15:41:43 EDT 2002


"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:

   def CompareOnSecondLetter(x,y): return cmp(x[1],y[1])
   a = ['apple', 'banana', 'pear', 'watermelon']
   a.sort(CompareOnSecondLetter)

There's a school of thought that says Python shouldn't have lambda
and you should have to use def and give every function a name, but
IMO that goes against the decision that functions are objects in
Python.  Python isn't Fortran.  

There's a middle ground that says the name "lambda" (which comes from
Lisp) wasn't a good choice and another name should have been used
instead, like maybe 'func', which does the same thing.  I guess that's
reasonable.  I'm used to lambda from Lisp but another name would
probably be less scary to non-Lisp-users.



More information about the Python-list mailing list