Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call different function for each list item

Tags:

python

Let's say I have a list like this:

[1, 2, 3, 4]

And a list of functions like this:

[a, b, c, d]

Is there an easy way to get this output? Something like zip, but with functions and arguments?

[a(1), b(2), c(3), d(4)]
like image 300
nathancahill Avatar asked Jan 26 '26 10:01

nathancahill


1 Answers

Use zip() and a list comprehension to apply each function to their paired argument:

arguments = [1, 2, 3, 4]
functions = [a, b, c, d]

results = [func(arg) for func, arg in zip(functions, arguments)]

Demo:

>>> def a(i): return 'function a: {}'.format(i)
...
>>> def b(i): return 'function b: {}'.format(i)
...
>>> def c(i): return 'function c: {}'.format(i)
...
>>> def d(i): return 'function d: {}'.format(i)
...
>>> arguments = [1, 2, 3, 4]
>>> functions = [a, b, c, d]
>>> [func(arg) for func, arg in zip(functions, arguments)]
['function a: 1', 'function b: 2', 'function c: 3', 'function d: 4']
like image 177
Martijn Pieters Avatar answered Jan 27 '26 23:01

Martijn Pieters