Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating functions inside loop with lambda expression in python

If I make two lists of functions:

def makeFun(i):     return lambda: i  a = [makeFun(i) for i in range(10)] b = [lambda: i for i in range(10)] 

why do lists a and b not behave in the save way?

For example:

>>> a[2]() 2 >>> b[2]() 9 
like image 900
Anssi Avatar asked Dec 03 '09 16:12

Anssi


People also ask

Can we use for loop in lambda expression Python?

Since a for loop is a statement (as is print , in Python 2. x), you cannot include it in a lambda expression.

Can you put a function inside a loop Python?

A Python for loop is used to loop through an iterable object (like a list, tuple, set, etc.) and perform the same action for each entry. We can call a function from inside of for loop.

How do you write a loop function in Python?

To create functions in a loop with Python, we can create a function that returns a function and call it. to define the make_f function that we can call in a loop to return a function. Then we can do whatever we want with the returned function.

Can we write nested lambda function in Python?

Python allows lambda nesting, i.e., you can create another lambda function inside a pre-existing lambda function. For nesting lambdas, you will need to define two lambda functions – an outer and an inner lambda function. When the outer lambda is called, the inner lambda creates a function.


2 Answers

As others have stated, scoping is the problem. Note that you can solve this by adding an extra argument to the lambda expression and assigning it a default value:

>> def makeFun(i): return lambda: i ...  >>> a = [makeFun(i) for i in range(10)] >>> b = [lambda: i for i in range(10)] >>> c = [lambda i=i: i for i in range(10)]  # <-- Observe the use of i=i >>> a[2](), b[2](), c[2]() (2, 9, 2) 

The result is that i is now explicitly placed in a scope confined to the lambda expression.

like image 149
Stephan202 Avatar answered Oct 20 '22 05:10

Stephan202


Technically, the lambda expression is closed over the i that's visible in the global scope, which is last set to 9. It's the same i being referred to in all 10 lambdas. For example,

i = 13 print b[3]() 

In the makeFun function, the lambda closes on the i that's defined when the function is invoked. Those are ten different is.

like image 23
Jonathan Feinberg Avatar answered Oct 20 '22 05:10

Jonathan Feinberg