Autogenerate functions (array of lambdas)

Chris Johnson effigies at gmail.com
Thu Sep 6 17:46:42 CEST 2007


On Sep 6, 3:44 am, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> Chris Johnson <effig... at gmail.com> 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 variable in the lambda.

Thanks. I figured there had to be a better way than what I was doing.




More information about the Python-list mailing list