Iterating over a function call

Gerald Britton gerald.britton at gmail.com
Mon Feb 1 11:50:36 EST 2010


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.

So.....I'm wondering if there is any interest in an apply() built-in
function that would work like map() does in 2.x (calls the function
with each value returned by the iterator) but return nothing.  Maybe
"apply" isn't the best name; it's just the first one that occurred to
me.

Or is this just silly and should I forget about it?

-- 
Gerald Britton



More information about the Python-list mailing list