lambda semantics in for loop

Denis S. Otkidach ods at strana.ru
Sun Jan 5 10:20:29 EST 2003


On 6 Jan 2003, Paul Foley wrote:

PF> > i inside lambda is a global variable.
PF>
PF> No it isn't.  Python has lexical scoping now, doesn't it?!

Global scope is nested too, of cause.  The term doesn't matter
here, since the same rule applies to any nested scope:

>>> def f():
...     l = []
...     for i in range(10):
...         l.append(lambda x: x+i)
...     return l
...
>>> l = f()
>>> l[0](0)
9

Python keeps reference to _scope_ where i (in lambda) was
defined, not to current value of i.  But object i refere to is
new for each step of loop:

>>> for i in range(10):
...     print id(i)
...
135289180
135289216
135289192
135289132
135289120
135289108
135289096
135289060
135289084
135289072

And here is working example with nested scopes:

>>> l = []
>>> def factory(i):
...     return lambda x: x+i
...
>>> for i in range(10):
...     l.append(factory(i))
...
>>> l[0](0)
0

PF> [There's only one binding for i, though; that's the problem.

No, that's not true: the object i is bound to changes, as you can
see from example above.

PF> Iteration isn't the same as recursion!]

-- 
Denis S. Otkidach
http://www.python.ru/      [ru]






More information about the Python-list mailing list