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.
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.
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.
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 = []
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With