List of python lambda functions without partial

I am trying to create a list of lambda functions in python using list comprehension. but it didn’t work

eg

fl=[lambda x: x**i for i in range(5)] 

I check another question, it basically generates the same function based on the i link.

so I also tried partially.

 from functools import partial fl=[partial(lambda x: x**i) for i in range(5)] 

but that didn't work either. Any help would be appreciated. cheers ~

+6
source share
3 answers

You are switching to areas of Python .

 fl=[lambda x, i=i: x**i for i in range(5)] 
+6
source

You successfully pass i by name.

 fl=[lambda x: x**i for i in range(5)] 

Each time lambda is executed, it associates the same function i with the function, so when the function is executed (later), it uses the current value of i (which will be 4). Instead, you should pass it as the default argument:

 fl=[lambda x, j=i: x**j for i in range(5)] 

Actually, I noticed that you are abusing partial . Here:

 fl = [partial(lambda x, y: y ** x, i) for i in range(5)] 

This also works.

+6
source

Another common workaround is to use closure:

 def create_f(i): def f(x): return x**i return f fl = [create_f(i) for i in range(5)] 
+4
source

Source: https://habr.com/ru/post/890531/


All Articles