scoping with lambda in loops

Pettersen, Bjorn S BjornPettersen at fairisaac.com
Tue Sep 16 23:48:45 CEST 2003


> From: Ian McMeans [mailto:imcmeans at telus.net] 
> 
> I was bitten by a bug today that depended on how lambda works. It took
> me quite a while to realize what was going on.
> 
> First, I made multiple lambda functions inside a loop, each of which
> depended on the current loop variable.
> 
> >>> a = []
> >>> for index in range(5):
> 	a.append(lambda: index)

      a.append(lambda index=index: index)

> Now, see if you can guess what the output was for each of the
> functions in the list a:
> >>> a[0](), a[1](), a[2](), a[3](), a[4]()
> I had expected it to be (0, 1, 2, 3, 4), but actually, it's:
> 
> (4, 4, 4, 4, 4)
> 
> This really surprised me. I guess what is happening is that each
> lambda knows what the context of execution is where it was defined,
> and doesn't actually evaluate until the function is called, and when
> it does evaluate, it uses the current value of the variable. 

yes.

> Is this related to static scoping? 

Probably... depending on what you're asking <wink>.

[...]

-- bjorn





More information about the Python-list mailing list