Skip to main content
Python & FastAPI Interviews Predict Output P0 Medium

Late-binding closures inside a loop

Predict what the list comprehension prints when all lambdas are called.

Official Reference

Code Snippet

funcs = [lambda x: x * i for i in range(3)]
print([f(10) for f in funcs])

Expected Output & Explanation

[20, 20, 20]

Python closures capture the variable binding i, not its value at each iteration. By the time the lambdas run, the loop has finished and i is 2, so every function multiplies by 2. Fix with default arg capture: lambda x, i=i: x * i.

Follow-up Interview Question · Why does lambda x, i=i: x * i bind each iteration’s value?

Module Context & References

Python · Predict the output & bug traps Widely asked Python gotchas: defaults, closures, scoping, copies and async
Personal Notes · Markdown

Technologies & Interview Topics Covered

Switch between short-term interview tracks and long-term 80/20 engineering depth to practice JavaScript internals, React rendering and hooks, timed frontend machine coding UI challenges, MeetaPro FG300, Blind 75 & NeetCode 150 DSA patterns, Python & FastAPI APIs, PostgreSQL query optimization & MVCC, Redis caching, Applied AI RAG pipelines & evaluations, and distributed system design.