scoping with lambda in loops

David Eppstein eppstein at
Wed Sep 17 04:59:21 CEST 2003

In article <KvP9b.49089$DZ.34699 at>,
 "martin z" <pxtl at> wrote:

> > 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?

How about this:

def makefunction(x):
    def thefunction():
        return x
    return thefunction

a = map(makefunction, range(5))

The identifiers are still a little uninformative, but it's hard to do 
better without more information from the original poster...

David Eppstein            
Univ. of California, Irvine, School of Information & Computer Science

More information about the Python-list mailing list