Autogenerate functions (array of lambdas)

Paul Rubin http
Thu Sep 6 04:44:38 EDT 2007


Chris Johnson <effigies 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.



More information about the Python-list mailing list