0

Can someone explain to me why this is occurring?

It looks like the print statement is getting lazily evaluated, but the question then is where does the v come from, since it should just be the argument.

In languages such as OCaml a closure (lambda statement) effectively takes a snapshot of its environment and uses that, but python seems here to use the newest environment...

d = {}

def printf(v):
  print(v)

for v in range(10):
  d[v] = lambda:printf(v)

d[1]() prints 9

in python2.7 and python3.6

Cjen1
  • 1,826
  • 3
  • 17
  • 47
  • 1
    v is equal to 9 so it prints 9 – Hippolippo Feb 18 '20 at 16:49
  • 3
    Does this answer your question? [What do (lambda) function closures capture?](https://stackoverflow.com/questions/2295290/what-do-lambda-function-closures-capture) – polku Feb 18 '20 at 16:55

0 Answers0