3

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)]
nathancahill
  • 10,452
  • 9
  • 51
  • 91

2 Answers2

10

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']
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • You're a force of nature. – nathancahill Nov 14 '15 at 05:05
  • Would a list comprehension perform better than the `map` alternative below? `map(lambda func, arg: func(arg), functions, arguments)` is arguably a little more succinct and pythonic. – nathancahill Nov 14 '15 at 06:38
  • @nathancahill: I disagree that that is more succint and pythonic. I find a list comprehension to be more readable, personally. The `lambda` adds another stack push, the two approaches will perform about the same, I think. I'll run a test. – Martijn Pieters Nov 14 '15 at 06:42
  • @nathancahill: the list comprehension is *marginally* faster, but I'd call this too close to call, really. 1 million repetitions gives me `1.9220080375671387` for the list comp and `1.9732530117034912` for the `map()` approach. – Martijn Pieters Nov 14 '15 at 06:44
  • Awesome, thanks @martijn-pieters. I'll stick with the list comprehension. – nathancahill Nov 14 '15 at 06:45
1
arguments = [1, 2, 3, 4]
functions = [a, b, c, d]

def process(func, arg):
    return func(arg)

results = map(process, functions, arguments)

define a function process to do the job, and use map to iterate the functions with its arguments

Hooting
  • 1,681
  • 11
  • 20