possibly trivial newbie list/array question

Alex Martelli aleax at aleax.it
Thu Aug 23 15:36:49 CEST 2001


"Paul Rubin" <phr-n2001 at nightsong.com> wrote in message
news:7xy9obovj8.fsf at ruckus.brouhaha.com...
> Can you tell me the actual purpose of list comprehension?
>
>         [f(x) for x in a]
>
> just seems like confusing syntactic hair that's otherwise equivalent
> to, though as we've seen sometimes slower than,
>
>         map(lambda x: f(x), a).

This would be better expressed as map(f, a), of course (and then
it WOULD no doubt be faster than the comprehension:-).


> Am I missing something?  Unless there's more to it than I see (which
> is quite possible), I don't understand why this feature made it into
> the language.

For much the same reasons it's always been in Haskell, I guess (the
language from which it was copied): it's a simple, succint expression
of an extremely common family of constructs.  List comprehensions
are more general than map, of course, as they can include if clauses
and multiple for clauses, but that's not the main point.  Rather,
it's like asking "the actual purpose of the ** operator" -- after
all, C and C++ do without it, so to somebody coming from such
languages it might just seem like confusing syntactic hair that's
otherwise equivalent to calling the pow function (in this case,
it's pow that is more general, since it also handles the three
argument case of (a**b)mod c far more speedily for large ints).

But if raising-to-power is a very frequent operation in your
programs, it's much handier to have it around as an operator --
just as, if building lists is a very frequent operation in
your programs, list comprehensions are much handier than maps
and lambdas (no doubt the reason they were put in Haskell).
So, here, Python copied from Fortran -- just as, for list
comprehensions, it copied from Haskell.

A language is a huge collection of delicate balancing acts,
of design compromises, among many conflicting objectives,
including handiness and minimalism.  Reducing the need for
lambda, and thus its frequence in idiomatic Python, by an
order of magnitude, was no doubt a motivator here:-).

Reminds me of a debate the other way 'round a few months
ago over on comp.lang.functional, where another guy was
utterly convinced that the addition of list comprehensions
to Python was THE major event in the history of Python, or
something like that... of course, he did have a Haskell
background in that case:-).


Alex






More information about the Python-list mailing list