3 ms·
But doesn't this just happen because n is a pointer? What would you expect it to print? 1,2,3,4?
by Shizka 10y ago
But doesn't this just happen because n is a pointer? What would you expect it to print? 1,2,3,4?
- ufo 10y agoIn Lua it prints 1,2,3,4. It has to do with each loop iteration behaving as if it declared a different variable instead of sharing the same variable across the loop. Anyway, the problem they were talking about is clearer when you are closing over stuff that other than the loop variable: fns = [] for n in [1,2,3,4]: x = n*10 def fn(): print(x) fns.append(fn)
- bb88 10y agoYeah... so I agree that's confusing. It's akin to: def x(y=[]): y.append(1) return y for z in range(4): print x() For your case, I recommend using partial functions, which were created for this type of issue. I think it's also cleaner than closures where x depends on an outside context.