scoping with lambda in loops
Dave Benjamin
dave at 3dex.com
Tue Sep 16 22:38:09 EDT 2003
"martin z" <pxtl at hotmail.com> wrote in message
news:KvP9b.49089$DZ.34699 at news04.bloor.is.net.cable.rogers.com...
> > a = []
> > for index in range(5):
> > a.append(lambda index=index: index)
> >
> > or maybe more concisely
> >
> > a = [lambda index=index: index for index in range(5)]
>
> You know how Python is supposed to be executable pseudocode? Well that
> stuff is farking ugly. If I handed pseudocode like that into any TA in
one
> of my classes, I'd be toast. Is there any way to do that in a legible
> manner?
The following reads pretty well to me:
>>> produce_value = lambda value: lambda: value
>>> a = [produce_value(index) for index in range(5)]
>>> a[3]()
3
Dave
More information about the Python-list
mailing list