scoping with lambda in loops

Andrew Koenig ark at acm.org
Tue Sep 16 18:13:08 EDT 2003


Ian> First, I made multiple lambda functions inside a loop, each of which
Ian> depended on the current loop variable.

>>>> a = []
>>>> for index in range(5):
>>>> 	a.append(lambda: index)


Ian> Now, see if you can guess what the output was for each of the
Ian> functions in the list a:
>>>> a[0](), a[1](), a[2](), a[3](), a[4]()
Ian> I had expected it to be (0, 1, 2, 3, 4), but actually, it's:

Ian> (4, 4, 4, 4, 4)

Ian> This really surprised me.

Suppose you did it this way:

        a = []
        for index in range(5):
            def foo():
                return index
            a.append(foo)

What result would you expect now, and why?

-- 
Andrew Koenig, ark at acm.org




More information about the Python-list mailing list