4

The following is a code snippet which I don't seem to get. The question is how to make the function output the desired result (not mentioning what the desired result is, I assume its printing 0 to 9).

Here is the question: What does the below code snippet print out? How can we fix the anonymous functions to behave as we'd expect?

functions = []
for i in range(10):
    functions.append(lambda : i)

for f in functions:
    print(f())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

6

In Python, no new scope will be produced in for loop

So after for i in range(10), the variable i is still exist, and its value == 9. And the lambda function lambda : i access the variable i

In order to output your desired result, you should pass the variable as a function argument in loop

functions = []
for i in range(10):
    functions.append(lambda i=i: i)

for f in functions:
    print(f())
Iv4n
  • 239
  • 1
  • 8