Re:The scope of index variables in Python's for loops
by rhizome31 on Sunday January 18, 2015 @03:42PM
(#8908790)
You can capture the index with a keyword argument default value:
def foo():
lst = []
for i in range(4):
lst.append(lambda i=i: i)
print([f() for f in lst])
FWIW I played around with this issue in various languages in this blog post: https://my.smeuh.org/al/blog/lost-in-scope
Once you get the difference between block scope and function scope, it's quite easy to see what's happening.
It appears that the lambda creates a closure for i, but i is defined in the outer scope and we capture the reference for i, rather than i's value.
So we can get around this:
It appears that i is dereferenced when passed to the first lambda constructor, which provides i's dereferenced value as a in a scope provided for the inner lambda. Please correct me if I am wrong, anyone?!--------Edit 2--------
Out of curiosity, I looked at this in Clojure and the way it creates lambdas is similar to Python (captures reference as opposed to value).
You could do something like this: But perhaps there is another way as well.