Iterating over a function call

Arnaud Delobelle arnodel at googlemail.com
Mon Feb 1 15:05:55 EST 2010


Gerald Britton <gerald.britton at gmail.com> writes:

> Hi -- I have many sections of code like this:
>
>     for value in value_iterator:
>          value_function(value)
>
> I noticed that this does two things I don't like:
>
> 1. looks up "value_function" and "value" for each iteration, but
> "value_function" doesn't change.
> 2. side effect of (maybe) leaking the iterator variable "value" into
> the code following the loop (if the iterator is not empty).
>
> I can take care of 2 by explicitly deleting the variable at the end:
>
>    del value
>
> but I'd probably forget to do that sometimes.  I then realized that,
> in the 2.x series, I can accomplish the same thing with:
>
>     map(value_function, value_iterator)
>
> and avoid both problems BUT map() returns a list which is never used.
> Not a big deal for small iterables, I guess, but it seems messy.  Upon
> conversion to 3.x I have to explicitly list-ify it:
>
>     list(map(value_function, value_iterator))
>
> which works but again the list returned is never used (extra work) and
> has to be gc'd I suppose (extra memory).
>
> It's easy to make a little function to take care of this (2.x):
>
>     from itertools import imap
>     def apply(function, iterable):
>         for item in imap(function, iterable):
>             pass
>
> then later:
>
>    apply(value_function, value_iterator)
>
> or something similar thing in 3.x, but that just adds an additional
> function def that I have to include whenever I want to do something
> like this.
>

You have itertools.consume which is close to what you want:

    consume(imap(func, iterable)) # 2.x

    consume(map(func, iterable)) # 3.x

HTH

-- 
Arnaud



More information about the Python-list mailing list