How to convert a list of values to a list of functions that return these values
Question:
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?
Answers:
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.
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
.
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?
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.
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
.