[Tutor] Lambda

Remco Gerlich scarblac@pino.selwerd.nl
Fri, 20 Jul 2001 20:23:42 +0200


On  0, "Tobin, Mark" <Mark.Tobin@attcanada.com> wrote:
> Is it fair to say that Lambda is just a shorthand for defining a function?

Yes. There are but a few differences between lambda and def:

- A lambda doesn't have a name.
- A lambda can only contain a single expression, of which the value is
  returned. No statements, control structures, etc.
- Lambda is an expression, so you can use it as a function argument,
  and so on. Def is a statement, you have to define a function first, then
  you can give it to some function.

> I really haven't figured it out, and don't know where one might use it...
> anybody willing to write a paragraph on Lambdas or point me to an
> explanation?

You sometimes want to make a short throwaway function to use as a function
argument, for instance to give a callback function to some GUI thingy, or as
an argument to functions like map:

L2 = map(lambda x: x*2, L)   # Returns a list with all elements of L doubled

That simply slightly easier to write than

def double(x):
   return 2*x
L2 = map(double, L)

In many cases, list comprehensions can be used now where map/lambda used to
be appropriate, and in my opinion at least they're more Pythonic:

L2 = [x*2 for x in L]

> maybe trying to figure out lambdas and recursion in the same week was too
> lofty a goal... ;-)

Well, recursion is a profound, fundamental concept, lambda is just a quick
notation :)

-- 
Remco Gerlich