[Tutor] lambda and map

Tim Peters tim.one@home.com
Sun, 27 May 2001 17:04:54 -0400


[alan.gauld@bt.com]
> Personal aside to the list...
> To be honest, in Python lamda is a bit limited
> - essentially to single line expressions.
> I'm not sure why we can't do:
> [multiple statement/expression lambdas]

[Kalle]
> I think because Guido wanted it crippled.

No, "lambda" was contributed code -- Guido had nothing to do with it apart
from approving the idea and applying the patch.

> He has later expressed the opinion that letting lambda in at all
> was a mistake.  Somebody who was out of diapers in the early
> 1990's might know. <wink>

I'm older than Guido, but that doesn't mean I've outgrown diapers <wink>.
Guido considered lambda (along with map(), filter() and reduce(), which were
contributed in the same patch that introduced lambda) "minor conveniences".
He still thinks of them that way at heart, although in public he's more
likely to call them "minor annoyances" now, because people who want *more*
from them than minor convenience are heading down a road Guido doesn't want
to see Python travel.  Functional programming styles aren't natural in
Python, and Guido doesn't intend to do anything to make them more natural.
So use these things when they're *obviously* useful, but never strain to
make code fit.

Natural:

    print len(x)

Strained:

    print reduce(lambda n, elt: n+1, x, 0)

Both print the length of a sequence x, but the second way is just silly in
Python.

Natural:

    print map(ord, "abc")

    print filter(lambda x: x & 1, list_of_ints) # extract the odd ints
    print [x for x in list_of_ints if x & 1]    # also natural

BTW, I don't believe I've ever seen a good use for reduce() in Python!  The
equivalent loop is almost always clearer, faster and easier to modify.