Given this snippet of code:
funcs = []
for x in range(3):
funcs.append(lambda: x)
print [f() for f in funcs]
I would expect it to print [0, 1, 2], but instead it prints [2, 2, 2]. Is there something fundamental I’m missing about how lambdas work with scope?
This is a frequent question in Python. Basically the scoping is such that when
f()is called, it will use the current value ofx, not the value ofxat the time the lambda is formed. There is a standard workaround:The use of
lambda x = xretrieves and saves the current value ofx.