Newbie ?:A more concise way?

Jeff Shannon jeff at ccvcorp.com
Tue Mar 5 15:33:02 EST 2002


Geoff Gerrietts wrote:

> Quoting Brian (brian at lodoss.org):
> > OK - now I have another question (and remember I'm new to Python) if
> > map and lambda are part of the core language and have well defined
> > behavior, why is it that using them is considered bad form?  Are they
> > just the redheaded step-children of the language, or what? ;-)
> ....
> I think that I have seen notables in the python community (I would
> name names, but I don't have quotes to reference) have indicated
> regret at the introduction of map() and friends into the language.
> They end up being appropriate only very, very rarely.
>
> The lambda construct doesn't suffer from quite the same stigma, though
> I think some feel that it's overused, and to bad effect.

To my understanding, you have this almost exactly backwards.  The functions
map(), filter(), etc, are standard functional-programming features and are very
useful, in the right places.  I can't recall them being specifically looked down
on, or regretted.  However, they are frequently used in places where list
comprehensions would do the job better.  List comps are a later addition to the
language, though, so many people familiar with map() et. al., prefer to keep
using them.

Lambdas, on the other hand, are the ugly child that looks just like the
postman...  With functional constructs like map() being added to the language,
functional programmers everywhere were begging for lambdas, as well (they're
used heavily in Lisp and other f.p. languages).  However, due to various reasons
(mostly issues with the Python parser, IIRC), Python lambdas are crippled --
they can only contain a single expression, so they aren't *quite* equivalent to
anonymous functions, but they still have the (relatively high) cost of a
function call.  They also have (IMHO) confusing syntax.

The big gain in using list comprehensions, comes from the fact that it often
eliminates the need to use an expensive (and, IMO, ugly) lambda.  The line

z = map(lambda x: MyClass(), range(y))

has y extra function calls (to the lambda) that are not present in

z = [MyClass() for x in range(y)]

Also note that the lambda doesn't really avoid the extra 'x' variable -- you're
still using it as a parameter to the lambda, which is then ignored.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list