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?