Python list of lambda functions

Question:

Say I need to build n lambda functions, and put them into a list:

n = 6
lamd_list = [lambda x: x * i for i in range(n)]

Here x is input of the lambda functions, and the i is intended to be fixed to 0~5 in the list. However, when I run:

lamb_list[0](3)

The output would be 15 (3 * 5) instead of 0 (0 * 5). How can I modify the code to make it do as I intended?
Note that here the n is a variable (not fixed), so I can’t do the loop manually. Also, I don’t want i as an input to the lambda function.

Asked By: Zhang Yu

||

Answers:

The value of i is not fixed when you defined the function, but when you call the function. You can fix it, but I would recommend not using lambda expressions at all. Instead, define a function that creates your function when called; it makes the scoping easier to handle.

def make_function(i):
    def _(x):
        return x * i
    return _

func_list = [make_function(i) for i in range(n)]

The difference here is that the i in the function that make_function returns is not a global variable, but the value of the parameter i when make_function is called.

Compare to another possible solution

lambd_list = [lambda x, unused=i: x * unused for i in range(n)]

which requires an otherwise unused parameter to be added to each function. The difference here is the default value of unused is evaluated at the same time as the lambda expression.

Answered By: chepner
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.