Skip to content
Preptima
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

Further reading

Related Topics