开发者

List comprehension and functions

I'm a little confusing whe开发者_C百科n 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?


This is due to how closures in Python work.

The loop changes the value in the scope that all the functions share. Move generation of the function into a separate scope, i.e. function.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜