views:

90

answers:

3

I'm a little confusing when try something like this

b = [lambda x:x**i for i in range(11)]

When I then try b[1](2) I have 1024 as a result that is wrong. But when I write so

b = [(lambda i: lambda x:x**i)(i) for i in range(11)]

all is OK

>>> b[1](2)
2
>>> b[5](2)
32

It works fine but what's wrong in first code?

+3  A: 

This is due to how closures in Python work.

Ignacio Vazquez-Abrams
+1  A: 

It's a game of scopes.

In the first code, the "i" name in the lambda is only a reference. The value behind that reference gets altered as the for loop executes.

In the second code, there are two different scopes.

Jeremy
A: 

Your question is not a duplicate, but the reasoning is the same as in the answers to this question.

jcdyer