Python create function in a loop capturing the loop variable

lambda, python

Solution

lambdas in python are closures.... the arguments you give it aren't going to be evaluated until the lambda is evaluated. At that time, i=9 regardless, because your iteration is finished.

The behavior you're looking for can be achieved with functools.partial

import functools

def f(a,b):
    return a*b

funcs = []

for i in range(0,10):
    funcs.append(functools.partial(f,i))

Problem

What's going on here? I'm trying to create a list of functions: ``` def f(a,b): return a*b funcs = [] for i in range(0,10): funcs.append(lambda x:f(i,x)) ``` This isn't doing what I expect. I would expect the list to act like this: ``` funcs[3](3) = 9 funcs[0](5) = 0 ``` But all the functions in the list seem to be identical, and be setting the fixed value to be 9: ``` funcs[3](3) = 27 funcs[3](1) = 9 funcs[2](6) = 54 ``` Any ideas?

Original source

Related problems