Creating functions in a list

Viewed 60

I have noticed that this construction

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

fails to produce the expected results, e.g.

[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 workaround, which is this pattern

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 whether this was a good idea. Could it in more complicated cases hide further nasty surprises?

1 Answers
Related