lambda ??

Paul Rubin http
Fri Aug 27 04:21:38 EDT 2004


fuzzyman at gmail.com (Michael Foord) writes:

> It starts by giving some basic examples using lambda. What I'm
> wondering is what's the actual difference between these two forms ?
> 
> pr = lambda s:s
> *and*
> def pr(s):
>     return s

They're the same.

> Is it just a basic example (and so in this case there is no
> difference).. or am I missing something. (What's the point of an
> 'anonymous' function... if you give a name to it !!).

It's like an anonymous expression.  Look at the statement

   x = a + b * c

That adds the expression 'a' to the expression 'b * c'.  If Python
didn't have anonymous expressions, you'd say something like

  temp = b * c
  x = a + temp

Anonymous just means you can use it as an intermediate result without
having to give it a name of its own.

Example:

      def derivative(f, x):    # find approximate value of f'(x)
        h = .0001
        return (f(x+h) - f(x)) / h

      def square(x):
        return x*x

      print derivative(square, 3)    # approximately 6

An anonymous function lets you do the same thing without having to
create a named function (like a temporary variable):

      print derivative(lambda x: x*x, 3)    # same thing

Using a lot of lambdas can be like using a lot of complicated, deeply
nested arithmetic expressions.  You have to exercise some judgement to
keep your code readable.  But there's a school of thought that says
lambda is a wart in Python and shouldn't be used.  That's as silly as
saying you should never say "a + b * c" and instead name every
subexpression with a temp variable.



More information about the Python-list mailing list