extended list comprehensions

Kragen Sitaker kragen at pobox.com
Tue May 28 18:19:24 EDT 2002


"Andrew Dalke" <dalke at dalkescientific.com> writes:
> F. Jamitzky:
> >It would be great to have something like a list comprehension for the
> >reduce function.
>  ...
> >and maybe it could be written as:
> >
> >{y=y+x for x in xs}      <-would be->         reduce(operator.add,xs)
> 
> I use reduce so infrequently that I wouldn't think this is useful.
> How often do you use it?

Not as often as I could.  It's general enough that just about any
aggregate operation can be expressed in terms of it, usually as simply
as it could be in a loop, and often more simply.

As a simple example, see
http://lists.canonical.org/pipermail/kragen-hacks/2002-May/000343.html
for 'map' and 'filter' are expressed in terms of 'reduce', in Python
and Common Lisp.

> That's enough to make me believe your syntax would be confusing.
> (As it is, 'reduce' is confusing.)

Which is probably why it's not used as much as it could be...

> But given that, if y doesn't exist before the {} is called, your
> argument is that it should implicitly be set to 0.  This then would
> be one of the few places in Python with a default value, outside of
> a function parameter definitions.

If reduce doesn't get a 'start' argument, it starts with y set to the
first item in the list; you could do the same for "reduce
comprehensions".

That said, I think "reduce comprehensions" as presented are a terrible
idea; unlike list comprehensions, they are not an improvement in
readability over the corresponding explicit loop, and they are not an
improvement in readability over the corresponding call to 'reduce'.




More information about the Python-list mailing list