mediumConceptCodingEntryMidSenior
Why do the functions you build inside a loop all end up returning the last value?
Python closures capture variables, not their current values, so functions created in a loop all read the same final loop binding unless you bind a value per iteration. It also connects scoping to the point an interviewer is testing.
5 min readUpdated 2026-08-15
Answer
Short answer
Closures close over the variable cell, not a snapshot of its value. In a loop, every nested function sees the same loop variable after the loop ends; bind the value with a default argument, a factory, or functools.partial.
Was this answer helpful?
Likely follow-ups
- Why does a comprehension inside a class body raise NameError for a class attribute?
- What is in a function's __closure__, and how would you read the captured value?
- How would you fix the loop with functools.partial instead of a default argument?
- Why does adding one assignment to a function change the meaning of every read of that name in it?
Related questions
- What is a closure, and how does one end up leaking memory?mediumAlso on closures4 min
- You build a LINQ query, then change the list it came from, then enumerate it. What do you get?mediumAlso on closures5 min
- You are given a paragraph of requirements, not a problem statement. What do you write first, and what do you deliberately not build?mediumAlso on scoping5 min
- How do retain cycles happen in Swift closures and delegates, and how would you find one in an app that is slowly leaking memory?mediumAlso on closures4 min