map/filter/reduce/lambda opinions and background unscientific mini-survey

Jp Calderone exarkun at
Sun Jul 3 07:09:28 CEST 2005

On Sun, 03 Jul 2005 01:01:18 -0400, Christopher Subich <spam.csubich+block at> wrote:
>Steven D'Aprano wrote:
>> comps. But reduce can't be written as a list comp, only as a relatively
>> complex for loop at a HUGE loss of readability -- and I've never used
>> Lisp or Scheme in my life. I'm surely not the only one.
>See my reply to your other post for a more detailed explanation, but I
>don't think that the for-loop solution is much less readable at all, and
>the additional complexity involved is simply setting the initial value
>and result for the accumulator.  The for-loop solution is even more
>flexible, because it can include anonymous code blocks and not just
>One caevat that I just noticed, though -- with the for-solution, you do
>need to be careful about whether you're using a generator or list if you
>do not set an explicit initial value (and instead use the first value of
>'sequence' as the start).  The difference is:
>_accum =
>for i in g: _accum = stuff(_accum,i)
>_accum = g[0]
>for i in g[1:]: _accum = stuff(_accum,i)

In either case, you want to write:

  i = iter(g)
  _accum =
  for elem in i:
    _accum = stuff(_accum, elem)

You also want to catch the StopIteration from that explicit .next() call, but that's an unrelated matter.


More information about the Python-list mailing list