scoping with lambda in loops

David Eppstein eppstein at ics.uci.edu
Tue Sep 16 22:59:21 EDT 2003


In article <KvP9b.49089$DZ.34699 at news04.bloor.is.net.cable.rogers.com>,
 "martin z" <pxtl at hotmail.com> 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                      http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science




More information about the Python-list mailing list