473,804 Members | 2,173 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Mix lambda and list comprehension?

Hi,
trying to mix lambda expresions and list comprehension
doesn't seem to work.
---
[lambda x:x+y for y in range(10)][9](2) 11 [lambda x:x+y for y in range(10)][4](2)

11
---
I expected the second expression to return 6.
What did I do wrong? Any hints?
Thanks
- Peter
Jul 18 '05 #1
4 3041
Try this:
[lambda x, y=y:x+y for y in range(10)][4](2)
6
It is important to bind y in a closure at the time
the lambda is defined. Otherwise, y remains unbound
until you invoke the function call. At that time, the most
recent value of y is the last value in the range loop (namely, 9).
Raymond Hettinger

"Peter Barth" <pe*********@ t-online.de> wrote in message
news:6f******** *************** ***@posting.goo gle.com...
Hi,
trying to mix lambda expresions and list comprehension
doesn't seem to work.
--- [lambda x:x+y for y in range(10)][9](2) 11 [lambda x:x+y for y in range(10)][4](2)

11
---
I expected the second expression to return 6.
What did I do wrong? Any hints?
Thanks
- Peter

Jul 18 '05 #2
pe*********@t-online.de (Peter Barth) wrote in message news:<6f******* *************** ****@posting.go ogle.com>...
Hi,
trying to mix lambda expresions and list comprehension
doesn't seem to work.
---
[lambda x:x+y for y in range(10)][9](2) 11 [lambda x:x+y for y in range(10)][4](2) 11
---
I expected the second expression to return 6.
What did I do wrong? Any hints?
Thanks
- Peter


It is a scope issue. The last value for y is used for all
the created lambdas. All lambdas users are bitten by that,
soon or later. The solution is to make y local to the
lambda function, with the optional argument trick:
[lambda x,y=y:x+y for y in range(10)][4](2)

6

Michele
Jul 18 '05 #3
Thanks a lot, works fine.
However, the solution does not really feel "pythonesqu e".
Is it considered a usability bug or fine as is?
- Peter

"Raymond Hettinger" <vz******@veriz on.net> wrote in message news:<hM******* ********@nwrdny 01.gnilink.net> ...
Try this:
[lambda x, y=y:x+y for y in range(10)][4](2) 6
It is important to bind y in a closure at the time
the lambda is defined. Otherwise, y remains unbound
until you invoke the function call. At that time, the most
recent value of y is the last value in the range loop (namely, 9).
Raymond Hettinger

"Peter Barth" <pe*********@ t-online.de> wrote in message
news:6f******** *************** ***@posting.goo gle.com...
Hi,
trying to mix lambda expresions and list comprehension
doesn't seem to work.
---
>> [lambda x:x+y for y in range(10)][9](2)

11>> [lambda x:x+y for y in range(10)][4](2)

11
---
I expected the second expression to return 6.
What did I do wrong? Any hints?
Thanks
- Peter

Jul 18 '05 #4
bo**@oz.net (Bengt Richter) wrote in message news:<bf******* ***@216.39.172. 122>...
On 15 Jul 2003 05:41:02 -0700, mi**@pitt.edu (Michele Simionato) wrote:
pe*********@ t-online.de (Peter Barth) wrote in message news:<6f******* *************** ****@posting.go ogle.com>...
Hi,
trying to mix lambda expresions and list comprehension
doesn't seem to work.
---
>>> [lambda x:x+y for y in range(10)][9](2) 11 >>> [lambda x:x+y for y in range(10)][4](2)
11
---
I expected the second expression to return 6.
What did I do wrong? Any hints?
Thanks
- Peter


It is a scope issue. The last value for y is used for all
the created lambdas. All lambdas users are bitten by that,
soon or later. The solution is to make y local to the
lambda function, with the optional argument trick:
> [lambda x,y=y:x+y for y in range(10)][4](2)

6


or you could capture y as constants in the lambdas ;-)
>>> [eval('lambda x:x+%s'%y) for y in range(10)][4](2)

6
Regards,
Bengt Richter


Thanks to God, there is a smile in your post!!

;)

Michele
Jul 18 '05 #5

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

Similar topics

2
1456
by: Chas Emerick | last post by:
In a comment off a post on lambda-the-ultimate, I noticed this little offhand remark: '''IIRC GvR is going to kill the various lambda, map,filter & reduce leaving just generator expressions/list comprehension.''' If this is considered generally true (at least in the straight-from-the-rumor-mill sense) I'm hoping someone here can either provide the backstory on this or point me in the direction of related discussions on python-dev...
53
3708
by: Oliver Fromme | last post by:
Hi, I'm trying to write a Python function that parses an expression and builds a function tree from it (recursively). During parsing, lambda functions for the the terms and sub-expressions are constructed on the fly. Now my problem is lazy evaluation. Or at least I think it is. :-)
26
3510
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...
181
8932
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.
30
2181
by: Mike Meyer | last post by:
I know, lambda bashing (and defending) in the group is one of the most popular ways to avoid writing code. However, while staring at some Oz code, I noticed a feature that would seem to make both groups happy - if we can figure out how to avoid the ugly syntax. This proposal does away with the well-known/obscure "lambda" keyword. It gives those who want a more functional lambda what they want. It doesn't add any new keywords. It doesn't...
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=]
22
2015
by: Cameron Laird | last post by:
QOTW: "... and to my utter surprise it worked." - Andrew Nagel on his move from wxPython to programming Tkinter in desperation "Python has more web application frameworks than keywords." - Skip Montanaro (but probably others going back years) Frithiof Andreas Jensen writes frankly on use of SNMP and netconf: http://groups.google.com/group/comp.lang.python/msg/662032bf92670fd7
2
1364
by: sofeng | last post by:
I would like to use the following recipe to transpose a list of lists with different lengths. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410687 Here is an example of what I would like to do: Python 2.5.1 (r251:54863, May 18 2007, 16:56:43) on cygwin Type "help", "copyright", "credits" or "license" for more information. , , , ]
21
1860
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
9711
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
9593
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10595
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10088
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...
1
7633
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5529
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
5668
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
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.