Re: Autogenerate functions (array of lambdas)

2007-09-06 Thread Chris Johnson
On Sep 6, 3:44 am, Paul Rubin wrote: > Chris Johnson <[EMAIL PROTECTED]> writes: > > a = [lambda: i for i in range(10)] > > print [f() for f in a] > > results in: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9] > > rather than the hoped for: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > The usual id

Re: Autogenerate functions (array of lambdas)

2007-09-06 Thread Hrvoje Niksic
Chris Johnson <[EMAIL PROTECTED]> writes: > What I want to do is build an array of lambda functions, like so: > > a = [lambda: i for i in range(10)] Use a factory function for creating the lambdas. The explicit function call will force a new variable binding to be created each time, and the lamb

Re: Autogenerate functions (array of lambdas)

2007-09-06 Thread David Stanek
On 9/6/07, Chris Johnson <[EMAIL PROTECTED]> wrote: > > What I want to do is build an array of lambda functions, like so: > > a = [lambda: i for i in range(10)] > > (This is just a demonstrative dummy array. I don't need better ways to > achieve the above functionality.) > > print [f() for f in a]

Re: Autogenerate functions (array of lambdas)

2007-09-06 Thread Duncan Booth
Chris Johnson <[EMAIL PROTECTED]> wrote: > 2) Is there a better or preferred method than the one I've found? > Use function default arguments to keep the current value of i at the point where you define the function. a = [(lambda n=i: n) for i in range(10)] -- http://mail.python.org/mailman/

Re: Autogenerate functions (array of lambdas)

2007-09-06 Thread Diez B. Roggisch
Chris Johnson schrieb: > What I want to do is build an array of lambda functions, like so: > > a = [lambda: i for i in range(10)] > > (This is just a demonstrative dummy array. I don't need better ways to > achieve the above functionality.) > > print [f() for f in a] > > results in: [9, 9, 9, 9

Re: Autogenerate functions (array of lambdas)

2007-09-06 Thread Paul Rubin
Chris Johnson <[EMAIL PROTECTED]> writes: > a = [lambda: i for i in range(10)] > print [f() for f in a] > results in: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9] > rather than the hoped for: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] The usual idiom is a = [lambda i=i: i for i in range(10)] That way i is not a free va