473,795 Members | 2,512 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

lambda-funcs problem

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.

Sep 19 '07 #1
5 1376
On Wed, 19 Sep 2007 04:39:44 -0700, dmitrey.kroshko wrote:
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
Sep 19 '07 #2
dm************* @scipy.org 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)]

Sep 19 '07 #3
On Behalf Of dm************* @scipy.org
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 make_adder(i):
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

Sep 19 '07 #4
Ryan Ginstrom <software <atginstrom.com writes:
How about:
>def make_adder(i):
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]
>>
Or if you want a one liner:

funcs = [(lambda i: lambda x: x+i)(i) for i in xrange(10)]

Stéphane

Sep 19 '07 #5
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)]
Sep 19 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

63
3421
by: Stephen Thorne | last post by:
Hi guys, I'm a little worried about the expected disappearance of lambda in python3000. I've had my brain badly broken by functional programming in the past, and I would hate to see things suddenly become harder than they need to be. An example of what I mean is a quick script I wrote for doing certain actions based on a regexp, which I will simlify in this instance to make the pertanant points more relevent.
26
3507
by: Steven Bethard | last post by:
I thought it might be useful to put the recent lambda threads into perspective a bit. I was wondering what lambda gets used for in "real" code, so I grepped my Python Lib directory. Here are some of the ones I looked, classified by how I would rewrite them (if I could): * Rewritable as def statements (<name> = lambda <args>: <expr> usage) These are lambdas used when a lambda wasn't needed -- an anonymous function was created with...
7
4372
by: Paddy McCarthy | last post by:
Hi, I am trying to use eval as little as possible but solve this problem. #If given:two or more lambda equations x=lambda : A < B y=lambda : C+6 >= 7 .... How do I create another lambda expression Z equivalent to
17
2005
by: mehmetmutigozel | last post by:
I was thinking about something like the following; >>> a= Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 't' is not defined >>> or
181
8917
by: Tom Anderson | last post by:
Comrades, During our current discussion of the fate of functional constructs in python, someone brought up Guido's bull on the matter: http://www.artima.com/weblogs/viewpost.jsp?thread=98196 He says he's going to dispose of map, filter, reduce and lambda. He's going to give us product, any and all, though, which is nice of him.
6
1990
by: jena | last post by:
hello, when i create list of lambdas: l=] then l() returns 'C', i think, it should be 'A' my workaround is to define helper class with __call__ method: class X: def __init__(self,s): self.s=s def __call__(self): return self.s.upper() l=]
4
2634
by: Xah Lee | last post by:
A Lambda Logo Tour (and why LISP languages using λ as logo should not be looked upon kindly) Xah Lee, 2002-02 Dear lispers, The lambda character λ, always struck a awe in me, as with other mathematical symbols. In my mind, i imagine that those obscure math
5
2164
by: Octal | last post by:
How does the lambda library actually works. How does it know how to evaluate _1, how does it recognize _1 as a placeholder, how does it then calculate _1+_2, or _1+2 etc. The source files seem a bit complicated so any explanation would be appreciated. Thanks
26
2732
by: brenocon | last post by:
Hi all -- Compared to the Python I know and love, Ruby isn't quite the same. However, it has at least one terrific feature: "blocks". Whereas in Python a "block" is just several lines of locally-scoped-together code, in Ruby a "block" defines a closure (anonymous function). To avoid confusion let's call them Ruby block-closures. I see them as just a syntax for defining
21
1855
by: globalrev | last post by:
i have a rough understanding of lambda but so far only have found use for it once(in tkinter when passing lambda as an argument i could circumvent some tricky stuff). what is the point of the following function? def addn(n): return lambda x,inc=n: x+inc if i do addn(5) it returns
0
9672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10214
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10164
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10001
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6780
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.