Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate several functions using a for loop in Python? [duplicate]

Tags:

python

I am trying to generate several functions with different parameter i (see below) using a for loop, but it seems that all these functions are using the last item of i's. Could anyone tell me how to handle this?

This is a simplified example. I actually need to generate more than 200 functions with different parameters.

funs = ()
for i in range(2):
    f = lambda x: x+i
    funs += (f,)

Then it turns out that the two functions do the same thing:

funs[0](1)

Output: 2

funs[1](1)

Output: 2

But I expect the first function to give a result of 1 rather than 2.

Thank you very much in advance.

like image 381
Ivy.Zheng Avatar asked Jul 12 '17 15:07

Ivy.Zheng


People also ask

Can you have multiple for loops in a function Python?

Nested For LoopsLoops can be nested in Python, as they can with other programming languages. The program first encounters the outer loop, executing its first iteration. This first iteration triggers the inner, nested loop, which then runs to completion.

How do you repeat a statement in Python?

Loop statements use a very specific syntax. Unlike other languages, Python does not use an end statement for its loop syntax. The initial Loop statement is followed by a colon : symbol. Then the next line will be indented by 4 spaces.


1 Answers

you have to break the dynamic binding to i, for instance by wrapping 2 lambdas together:

f = (lambda p : lambda x: x+p)(i)

that way, the value of i is captured, and functions hold a copy of i

Aside: I wouldn't use tuple to create the list for performance reasons when appending to funs (funs = () => funs = [])

like image 147
Jean-François Fabre Avatar answered Oct 23 '22 03:10

Jean-François Fabre