Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list of python lambda functions w/o partial

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~

like image 575
Jerry Gao Avatar asked Jun 14 '11 18:06

Jerry Gao


2 Answers

You're tripping over Python scopes.

fl=[lambda x, i=i: x**i for i in range(5)]
like image 113
Ignacio Vazquez-Abrams Avatar answered Nov 15 '22 06:11

Ignacio Vazquez-Abrams


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.

like image 44
senderle Avatar answered Nov 15 '22 07:11

senderle