lambda-funcs problem

D

dmitrey.kroshko

hi all,
I need to create a Python list of lambda-funcs that are dependent on
the number of the ones, for example

F = []
for i in xrange(N):
F.append(lambda x: x + i)

however, the example don't work - since i in end is N-1 it yields x+
(N-1) for any func.

So what's the best way to make it valid?
Evaluation speed is also very important to me.

Thank you in advance, D.
 
M

Marc 'BlackJack' Rintsch

I need to create a Python list of lambda-funcs that are dependent on
the number of the ones, for example

F = []
for i in xrange(N):
F.append(lambda x: x + i)

however, the example don't work - since i in end is N-1 it yields x+
(N-1) for any func.

So what's the best way to make it valid?

The variable is bound to the name `i` when the lambda function is
created not to the value that `i` had at that time. The idiomatic way is
to use a default value for an argument because those are evaluated at
definition time of functions::

F.append(lambda x, i=i: x + i)

Ciao,
Marc 'BlackJack' Rintsch
 
B

Bruno Desthuilliers

(e-mail address removed) a écrit :
hi all,
I need to create a Python list of lambda-funcs that are dependent on
the number of the ones, for example

F = []
for i in xrange(N):
F.append(lambda x: x + i)

however, the example don't work - since i in end is N-1 it yields x+
(N-1) for any func.

So what's the best way to make it valid?

It's a FAQ. The answer is (using list-comp instead of a for loop):

funcs = [lambda x, i=i : x + i for i in xrange(n)]
 
R

Ryan Ginstrom

On Behalf Of (e-mail address removed)
F = []
for i in xrange(N):
F.append(lambda x: x + i)

however, the example don't work - since i in end is N-1 it yields x+
(N-1) for any func.

How about:
def adder(x):
return x+i
return adder
funcs = [make_adder(i) for i in xrange(10)]
print [func(10) for func in funcs] [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Regards,
Ryan Ginstrom
 
B

Bruno Desthuilliers

Stéphane Larouche a écrit :
(snip)
funcs = [(lambda i: lambda x: x+i)(i) for i in xrange(10)]

A bit more complex than necessary... The canonical solution is
funcs = [lambda x, i=i: x+i for i in xrange(10)]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,196
Latest member
ScottChare

Latest Threads

Top