extended list comprehensions

Andrew Dalke dalke at dalkescientific.com
Sun May 26 18:58:29 EDT 2002


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?

Your syntax is similar to "dictionary comprehensions" which have been
suggested several times, as in

  {x:x*x for x in xs}

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

reduce takes an optional 3rd arg, as in

>>> reduce(operator.add, "test", "prefix-")
'prefix-test'
>>>

which I guess you would support as

y = "prefix-"
{y=y+x for x in xs}

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.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list