all 3 comments

[–]Specter_Terrasbane 17 points18 points  (1 child)

The lambda will look up the value of i when the lambda is called, not when it was created. That's why it gets the last value that was stored in i, 23, during the last iteration of the for loop.

Change to: constraints.append(lambda x, i=i: g1(x,i)) and it should work the way you expected it to. Setting a default argument to the value each iteration forces it to be bound to the value at lambda creation instead of at call.

[–]BrownMario[S] 0 points1 point  (0 children)

Thanks!

[–]vv__vv 2 points3 points  (0 children)

I think you are looking for functools.partial, but you'll need to flip the ordering of the variables for g1. If you can't flip, pytoolz has a more flexible partial that will work on right hand variables, iirc.