Home > Mobile >  Elegant way to map a list of functions onto a variable in Python
Elegant way to map a list of functions onto a variable in Python

Time:09-20

Let's say I have an input variable:

var = 10

and I have a list of functions:

functions = [
  lambda x: x   1,
  lambda x: x   10,
  lambda x: x   42
]

Is there an elegant way to map the functions over the variable to get a list output?

# elegant one-liner here
11
20
52

P.S. not [f(var) for f in functions], please, something with map.

CodePudding user response:

You can use map for this, as the question suggests:

map(lambda f: f(var), functions)

For future reference, lambda f:f(var) takes a function, and applies that function to a value - which is what we want to do for each element of our list, so then we map it to our list, to apply this lambda function to each element of our list, calling that element with the variable var as an argument.

However, as jonrsharpe mentioned in the comments, if you're not just iterating over the map then a list comprehension is more in line with the standard Python style guide.

As a final aside for future reference, even if you're just iterating over it you could consider using a generator expression, which has many of the benefits of map.

CodePudding user response:

Using apply:

var = 10

functions = [
  lambda x: x   1,
  lambda x: x   10,
  lambda x: x   42
]

result = map(apply, functions, [[var]] * len(functions))

print(result)

Output (Try it online!):

[11, 20, 52]

Ah, good old times...

Python 3:

from operator import methodcaller
from functools import partial

var = 10

functions = [
  lambda x: x   1,
  lambda x: x   10,
  lambda x: x   42
]

result = list(map(partial(methodcaller('__call__', var)), functions))

print(result)

Output (Try it online!):

[11, 20, 52]
  • Related