How to make a list of functions in python?

Question:

I tried to achieve something like this

list1 = [lambda x: x+0, lambda x: x+1]

by doing this

list2 = [lambda x: x+n for n in range(2)]

But it doesn’t work! (Why not?)
How do I create a list of functions programmatically?

Asked By: Ziofil

||

Answers:

n is reassigned by the for expression, so after the for expression is completed both will see value of n being 1.

More typical example of this problem can be visible without list expression:

list3 = []
for n in range(2):
    def f(x):
        return x + n
    list3.append(f)

Here also all created function objects will refer to the same variable n and it will be assigned value 1 and both function objects will work as lambda x: x + 1.

You can deal with it by creating additional scope with a variable for each created function:

a = [(lambda n: lambda x: x+n)(n) for n in range(2)]
Answered By: zch
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.