lambda expressions

Steve Horne steve at lurking.demon.co.uk
Mon Feb 4 08:03:16 EST 2002


On Sun, 3 Feb 2002 12:52:48 +0100, Bas van Gils <bas.vangils at home.nl>
wrote:

>Pythonians,
>
>I've been wondering, lately, about lambda-expressions. Most programming
>languages support and I wondered why (mostly because I find them hard to
>read, valueing _readable_ code). Collegues at work couldn't give me a
>satisfying answer so ... can anyone explain to me why lambda-expressions
>are so useful?
>
>thankx in advance
>
>    Bas

First off, I don't think most languages support lambda expressions.
It's really just languages which have a functional influence.

In functional languages, the reason is simply that they are based
heavily on lambda calculus, and therefore need to be able to express
all the core concepts from lambda calculus.

In Python, it's more to do with convenience and readability when
passing functions as parameters. If the function to be passed is very
simple, it is easier to define it as an anonymous lambda because it
saves having to write a named function elsewhere, and it saves future
readers from having to look up a separate function elsewhere in the
code.

Consider trying to read the following code...

  print wibble (a, b)

You'd be pretty annoyed to find that the definition, 1000 lines of
code away, was...

  def wibble (a, b) :
    return a + b

You'd much rather see...

  print a + b


Similarly, this...

  print map (lambda x : x*2, [1,2,3])

...is clearer than...

  def wibble (x) :
    return x*2

  <thousands of lines of code>

  print map(wibble, [1, 2, 3])


Though only if you understand the 'lambda', of course.

-- 
Steve Horne
steve at lurking.demon.co.uk



More information about the Python-list mailing list