I have been trying to generate a list of lambda functions in python using list comprehension. but it didn't work,
for example
fl=[lambda x: x**i for i in range(5)]
i have check the other question, it basically generate the same function based on the reference of i.
so I also tried partial.
from functools import partial
fl=[partial(lambda x: x**i) for i in range(5)]
but it didn't work too. any help will be appreciated. cheers~
You're tripping over Python scopes.
fl=[lambda x, i=i: x**i for i in range(5)]
You're effectively passing i
in by name.
fl=[lambda x: x**i for i in range(5)]
Every time lambda
is executed, it binds the same i
to the function, so when the function is executed (later) it uses the then-current value of i
(which will be 4). You should pass it in as a default argument instead:
fl=[lambda x, j=i: x**j for i in range(5)]
Actually, I noticed that you're misusing partial
. Here:
fl = [partial(lambda x, y: y ** x, i) for i in range(5)]
That works as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With