0

Consider the following piece of code:

closures = {}

for i in range(5):
  def closure():
    print(i)
  closures[i] = closure

for k,_ in closures.items():
  closures[k]()

Intuitively I would expect the output to be (newline separated) "0 1 2 3 4". But the output is actually "4 4 4 4 4" (each number on a new line).

My question is, why does it do that and how can I get it to print what I would expect?

juniper-
  • 6,262
  • 10
  • 37
  • 65
  • 2
    The closure captures the NAME, not the VALUE. When the functions are executed, the value of `k` is 4. Use `def closure(i=i):` to "capture" the value. – Tim Roberts Aug 30 '22 at 00:03
  • 1
    Consider; `def foo(): print(x)`; then do `x = 3; foo()`, what do you expect / see? then `x = 100; foo()`, and what do you expect / see? – juanpa.arrivillaga Aug 30 '22 at 00:07

0 Answers0