Creating functions in a list

I noticed that this construction

funcs = [lambda x: x**n for n in range(5)]

      

does not give expected results like

[f(0.5) for f in funcs]
# [0.0625, 0.0625, 0.0625, 0.0625, 0.0625]

      

What is the canonical solution to this problem? I have my own solution which is a step

def function_maker(n):
    return lambda x: x**n

funcs = [function_maker(n) for n in range(5)]
[f(0.5) for f in funcs]
# [1.0, 0.5, 0.25, 0.125, 0.0625]

      

I wondered if this was a good idea. Could this, in more complex cases, hide further unpleasant surprises?

+3


source to share


1 answer


This is pretty canonical as you need to create a closure over n

in order to store the value.
You can do it as one liner, but it's ugly:



>>> funcs = [(lambda e: lambda x: x**e)(n) for n in range(5)]
>>> [f(0.5) for f in funcs]
[1.0, 0.5, 0.25, 0.125, 0.0625]

      

+4


source







All Articles