functional programming with map()

Andrae Muys amuys at shortech.com.au
Mon Mar 4 23:23:45 EST 2002


"Raymond Hettinger" <python at rcn.com> wrote in message news:<a5v14m$8d9$1 at bob.news.rcn.net>...
> "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 )
> 

Well while I'm drooling with anticipation with the approach of lazy
builtin's and generator comprehensions, they aren't much help here
where the problem was to "call f on x for x in items", compared to
what you suggest which is "call f with x for x in items".

Andrae



More information about the Python-list mailing list