1

I am trying to convert a list of return values to a list of functions that return these values.

lst = [1, 2]
funcs = [lambda: x for x in lst]

this is equivalent to:

x = 2
funcs = [lambda: x, lambda: x]

but I am trying to get:

funcs = [lambda: 1, lambda 2]

This question explains why this is happening, but doesn't provide a way to do it.

Is there any way to achieve this?

spmdc
  • 338
  • 3
  • 13

2 Answers2

4

This will work:

[lambda x=x: x for x in lst]

Explanation: This creates a new function parameter x which gets initialized with the default value currently set to the loop parameter x. When you call the method without parameters, the default will be returned.

I suggest to use different names to make it less confusing:

[lambda result=i: result for i in lst]

Another approach is to write your own lambda-like function which defines nested functions that it returns.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
2

You can use:

def f(x):
    return lambda: x

funcs = [f(x) for x in lst]

This approach might in particular be useful if the functions are more complicated, because here you can put an arbitrary function definition into the body of f.

piripiri
  • 1,925
  • 2
  • 18
  • 35