0

Consider the following Python code snippet:

fns = []
for i in range(2):
    x = i
    fns.append(lambda: x)
for fn in fns:
    print(fn())

Why does this print

1
1

instead of

0
1
jpr
  • 3
  • 1
  • Python uses late-binding and lexical scoping. `i` is a free-variable closed over the anonymous functions you created. It always refers to the `i` in the global scope. Note, `print(i)` after your for-loop. The "correct" way to do this is to use another enclosing scope: `.append((lambda x: lambda : x)(i))`. There is also a hack, which involves using default-arguments: `.append(lambda i=i: i)`. This isn't exactly equivalent, since now your anonymous functions have a default argument, but it works because default arguments are evaluated once at function definition time – – juanpa.arrivillaga Feb 23 '18 at 20:07
  • so just `for i in range(2): fns.append((lambda x: lambda: x)(i))` – juanpa.arrivillaga Feb 23 '18 at 20:09

1 Answers1

2

The lambda function is printing the value of the variable x:

fns = []
for i in range(2):
    x = i
    fns.append(lambda: x)

x = 4

for fn in fns:
    print(fn())
#4
#4
pault
  • 41,343
  • 15
  • 107
  • 149