Questions / Quant development, Python correctness
Capture a loop variable
In Python, what is sum(f() for f in fs)?
fs = [lambda: i for i in range(3)]
Answer it in the app It's free. You get hints, a second try if you miss, and a follow-up question.
Show the answer and worked solution
Answer: 6 value
- All three lambdas look up the same loop variable after the loop, when i=2. The sum is 2+2+2=6.
Interview shortcut. Closures bind late: every lambda sees the final i = 2.
In the app this has a follow-up where one thing about the setup changes. Try the follow-up.