Applying a Function to Each Item in a Python Iterable
I don’t know who needs to see this, or who—if anyone—will benefit by something so basic. As someone who has a pretty good familiarity with functional programming, often times I find myself wanting to execute a single function such as `print` for each item in an iterable being passed in as an argument one at a time. Now don’t get me wrong, `map` is great, but I’ve gotten so tired of having to wrap it with `list` every time just to bypass the lazy loading. It just feels like too many parenthesis for such an endeavor. I could use a list comprehension of course, but that too comes off as an excessive use of force.
Frankly, I was somewhat surprised a small utility like this didn’t exist as a component in the functools or itertools modules being as the standard library is already so vast. Perhaps it does, and I just haven’t found it yet. Anyways—without further ado, this is my solution to a small but nagging annoyance:
def applymap(fn, iterable, *args, **kwargs):
for item in iterable:
fn(item, *args, **kwargs)
fruits = ['Apple', 'Orange', 'Banana']
applymap(print, fruits)
applymap(print, fruits, end=' Basket\n')
It even plays nice with partials:
from functools import partial
print_basket = partial(print, end=' Basket\n')
applymap(print_basket, fruits)
Hopefully this is of use to someone out there. And if anyone who reads this knows of some component hidden away in the standard library that does this already, feel free to drop a comment—it would be much appreciated. Over and out.