list of polynomial functions
Scott David Daniels
scott.daniels at acm.org
Thu Jun 15 16:36:34 EDT 2006
Fredrik Lundh wrote:
> Tim Chase wrote:
>>> The `i` is the problem. It's not evaluated when the lambda
>>> *definition* is executed but when the lambda function is
>>> called. And then `i` is always == `n`. You have to
>>> explicitly bind it as default value in the lambda definition:
>>>
>>> polys.append(lambda x, i=i: polys[i](x)*x)
>>>
>>> Then it works.
>>
>> Just to sate my curiosity, why can the lambda find "polys", but not
>> find "i"? If what you're describing is the case, then it seems to me
>> that the following code should work too:
>
> it's not that it cannot find it, it's that if you use a closure, i will
> have the same value for all lambdas.
>
>> There's some subtle behavior here that I'm missing.
>
> lexical closures bind to names, default arguments bind to values.
Just to be a bit more explicit:
In code like:
def make_polys(n):
"""Make a list of polynomial functions up to order n."""
p = lambda x: 1
polys = [p]
for i in range(n):
polys.append(lambda x: polys[i](x)*x)
i=3
The lambda-defined functions will be called after the for loop is done,
at which time the "i" (from the surrounding environment) will have a
value of 3. Hope this makes it a bit clearer.
--Scott David Daniels
scott.daniels at acm.org
More information about the Python-list
mailing list