3 ms·
You can capture the index with a keyword argument default value: def foo(): lst = [] for i in range(4): lst.app
by rhizome31 12y ago
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 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.