functional programming with map()

Raymond Hettinger python at rcn.com
Mon Mar 4 00:36:10 EST 2002


"Andrae Muys" <amuys at shortech.com.au> wrote in message
news:7934d084.0202251545.5fb4bbf3 at posting.google.com...
> Paul Rubin <phr-n2002a at nightsong.com> wrote in message
news:<7xbseeayxk.fsf at ruckus.brouhaha.com>...
> > "Emile van Sebille" <emile at fenx.com> writes:
> >
> > > "Paul Rubin"
> > > > 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.
> > >
> > > If you know it's coming, throw it away first:
> > >
> > > [x.f() and None for x in items]
> >
> > OK, but that buidls a list of None as long as the item list.  Not
> > so bad, since it gets reclaimed right away, but still unsatisfying.
> >
> > > filter(None,[x.f() and None for x in items])
> > >
> > > returns an empty list vs 0 for the reduce.
> >
> > Again there's this intermediate list that's as long as the original
list.
> >
> > Do you see a way around that?
> >
>
> filter(lambda x:x.f() and 0, items) ?
>
> It's identical to the the reduce method posted previously, but avoids
> the tuple indexing required by reduce's use of a binary operator vs.
> filter's unary.
>
> Of course my first preference would be the list comprehension,
> discarding the redundant list, and if that was prohibitively expensive
> falling back to the original imperative style.
>

Are you sure that you don't prefer the PEP 279 alternatives:
xmap(), xfilter(), xzip() or generator comprehensions?

   [ yield f(x) for x in items ]

                or

   xmap( f, items )


Raymond Hettinger





More information about the Python-list mailing list