Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda Function Call [duplicate]

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())
like image 334
Tapajyoti Bose Avatar asked Oct 19 '25 00:10

Tapajyoti Bose


1 Answers

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())
like image 187
Iv4n Avatar answered Oct 20 '25 13:10

Iv4n