Fastest way to apply a function to an iterable

Stefan Behnel stefan_ml at behnel.de
Wed May 26 16:26:34 EDT 2010


Shashank Singh, 26.05.2010 21:48:
> What is the most efficient way of applying a function to all the elements of
> an iterable while discarding the
> result (i.e. operations are done only for side-effects).
>
> For example if I want to save all elements in a list of items (and am not
> interested in what save() returns), the
> simplest way is:
>
> itemlist = [i1, i2, i3....]
> for item in itemlist: item.save()
>
> It might be squeezing too much but is it possible to do it more efficiently
> by pushing the looping inside the C code
> and achieve some gains as is done by using map in place of a for loop when
> the return values need to be saved?

If all items have the exact same type, you can get away with an unbound method:

     class MyType(object):
         ...
         def safe(self):
             ...

     itemlist = [ MyType() for i in range(20) ]

     # this is what you want:

     from itertools import imap
     for _ in imap(MyType.save, itemlist): pass


But some people may consider this too ugly to actually use in real code.

Stefan




More information about the Python-list mailing list