functional programming with map()

Paul Rubin phr-n2002a at nightsong.com
Mon Feb 25 05:18:53 CET 2002


David Eppstein <eppstein at ics.uci.edu> writes:
> > : But what is the functional equvalent of:
> > 
> > : for x in items:
> > :     x.f()
> > 
> > 
> > 
> > Here's one way to do it:
> > 
> > ###
> > map(lambda x: x.f(), items)
> > ###
> 
> I'd prefer
> [x.f() for x in items]
> 
> It's not functional syntax, but so what?

Both of those build up a new list of the results, instead of
discarding the values.  If the f function takes an integer and
computes a 20-megabyte structure, you've got a problem.  This really
calls for a generator comprehension as discussed a few weeks back.

   reduce(lambda x,y:(y.f(),0)[1], items, 0)

almost works, but invokes f an extra time at the end.

Someone see how to fix it?



More information about the Python-list mailing list