473,799 Members | 3,121 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

question about what lamda does

Hey there,
i have been learning python for the past few months, but i can seem to
get what exactly a lamda is for. What would i use a lamda for that i
could not or would not use a def for ? Is there a notable difference ?
I only ask because i see it in code samples on the internet and in
books.

thanks for any clarity

sk

Jul 18 '06
16 1571
tac-tics wrote:
ne*****@xit.net wrote:
>>Hey there,
i have been learning python for the past few months, but i can seem to
get what exactly a lamda is for. What would i use a lamda for that i
could not or would not use a def for ? Is there a notable difference ?
I only ask because i see it in code samples on the internet and in
books.


Lambda is just as powerful as a function, but totally useless =-P

Lambda used to be handy before the introduction of list comprehensions.
Now, though, there primary use is obfuscating your code.
I do wish you could hold yourself back and stop muddying the waters.
Lambdas and list comprehensions have little or nothing to do with each
other. Unless you know something I don't ...

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Jul 19 '06 #11

Steve Holden wrote:
tac-tics wrote:
ne*****@xit.net wrote:
>Hey there,
i have been learning python for the past few months, but i can seem to
get what exactly a lamda is for. What would i use a lamda for that i
could not or would not use a def for ? Is there a notable difference ?
I only ask because i see it in code samples on the internet and in
books.

Lambda is just as powerful as a function, but totally useless =-P

Lambda used to be handy before the introduction of list comprehensions.
Now, though, there primary use is obfuscating your code.
I do wish you could hold yourself back and stop muddying the waters.
Lambdas and list comprehensions have little or nothing to do with each
other. Unless you know something I don't ...
I think he meant that lambda's main use before was inside map and
filter; as stated earlier in the thread, lambda's main use was for
passing simple functions as arguments, and of these map and filter must
have made up a majority (and then I'd guess TKinter would be next).
List comprehensions replace map and filter, so...

I wouldn't put it as explosively as he has, but I find a lambda less
clear than a def too.

Iain

regards
Steve

--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
Jul 19 '06 #12
ne*****@xit.net wrote:
Hey there,
i have been learning python for the past few months, but i can seem to
get what exactly a lamda is for. What would i use a lamda for that i
could not or would not use a def for ? Is there a notable difference ?
I only ask because i see it in code samples on the internet and in
books.

thanks for any clarity

sk
hehe. Lambda's are kind of a sensative subject for pythoners who come
from Lisp. Guido being more of a C guy doesn't really like them, and
thought they should be removed in py3k. Last time I checked, he was
reconsidering because of public outcry, presumably from the Lisp crowd.

The standard reason for getting rid of it is "anywhere you need a
lambda, you can use a def". In addition to what has been said here,
there is another one small difference between lambda's and functions,
which is that when you use def, the object gets a name:
>>def foo(): pass
....
>>foo
<function foo at 0x009D8230>
# ^ foo knows its own name
>>bar
<function foo at 0x009D8230>
# ^ see ;)
>>>
Whereas, a lambda has no name; it's "anonymous" :
>>spam = lambda: 1
spam
<function <lambdaat 0x009D80F0>
# ^ spam has an identity crisis ;)
>>>
Many people who do not come from Lisp do not understand what the use of
a lambda is (and I have no idea what the purpose of having a name is).
Even people who do question whether it belongs in Python. In Lisp,
lambda's are the way things get done, because you can calculate
anything using just defines and expressions. This style does not fit
Python very well, since we do things using statements.

Python's lambda really can't be as powerful as Lisp's because Python
does not have expressions that do case analysis (this is not lambda's
fault, of course ;). The reason is that you really want to put each
case on its own set of lines. This enhances readability at the expense
of terseness. Since Python's statements are terminated by a newline, it
would be rather awkward to have a kind of expression where good style
calls for it to be spread out accross multiple lines.

You can try to simulate these kinds expressions using into a list or
dictionary, but this becomes rather messy. I think the only way to get
this done properly is to use eval. For example:

def recursiveFuncti on(args):
... # do stuff...
choices = { True:"0", False:"recurisv eFunction(newAr gs)" }
return eval( choices[predicate] )

The reason that you need eval is that you want to prevent any cases
from being executed until you decide which one you want. This stay of
execution is accomplished by wrapping quotes around our expressions.
This example illustrates why we really need this kind of behavior,
because without it, we would fall into an infinite loop. Even if it
were safe to evaluate all cases, it's a big waste of time to do so.

Lastly, I think there is also a performance concern for certain uses of
lambda (correct me if I'm wrong). Say you have an expression with a
lambda in it where you could have used a def. Every time you evaluate
that expression, you have to construct a new lambda object, which takes
time. If you had used a def instead, you could hav avoided having to
construct multiple times.

Jul 20 '06 #13
hey thanks for that last post, although some of it was a bit over my
head.
i think i am getting more of the differences here.

thanks again,
sk

danielx wrote:
ne*****@xit.net wrote:
Hey there,
i have been learning python for the past few months, but i can seem to
get what exactly a lamda is for. What would i use a lamda for that i
could not or would not use a def for ? Is there a notable difference ?
I only ask because i see it in code samples on the internet and in
books.

thanks for any clarity

sk

hehe. Lambda's are kind of a sensative subject for pythoners who come
from Lisp. Guido being more of a C guy doesn't really like them, and
thought they should be removed in py3k. Last time I checked, he was
reconsidering because of public outcry, presumably from the Lisp crowd.

The standard reason for getting rid of it is "anywhere you need a
lambda, you can use a def". In addition to what has been said here,
there is another one small difference between lambda's and functions,
which is that when you use def, the object gets a name:
>def foo(): pass
...
>foo
<function foo at 0x009D8230>
# ^ foo knows its own name
>bar
<function foo at 0x009D8230>
# ^ see ;)
>>

Whereas, a lambda has no name; it's "anonymous" :
>spam = lambda: 1
spam
<function <lambdaat 0x009D80F0>
# ^ spam has an identity crisis ;)
>>

Many people who do not come from Lisp do not understand what the use of
a lambda is (and I have no idea what the purpose of having a name is).
Even people who do question whether it belongs in Python. In Lisp,
lambda's are the way things get done, because you can calculate
anything using just defines and expressions. This style does not fit
Python very well, since we do things using statements.

Python's lambda really can't be as powerful as Lisp's because Python
does not have expressions that do case analysis (this is not lambda's
fault, of course ;). The reason is that you really want to put each
case on its own set of lines. This enhances readability at the expense
of terseness. Since Python's statements are terminated by a newline, it
would be rather awkward to have a kind of expression where good style
calls for it to be spread out accross multiple lines.

You can try to simulate these kinds expressions using into a list or
dictionary, but this becomes rather messy. I think the only way to get
this done properly is to use eval. For example:

def recursiveFuncti on(args):
... # do stuff...
choices = { True:"0", False:"recurisv eFunction(newAr gs)" }
return eval( choices[predicate] )

The reason that you need eval is that you want to prevent any cases
from being executed until you decide which one you want. This stay of
execution is accomplished by wrapping quotes around our expressions.
This example illustrates why we really need this kind of behavior,
because without it, we would fall into an infinite loop. Even if it
were safe to evaluate all cases, it's a big waste of time to do so.

Lastly, I think there is also a performance concern for certain uses of
lambda (correct me if I'm wrong). Say you have an expression with a
lambda in it where you could have used a def. Every time you evaluate
that expression, you have to construct a new lambda object, which takes
time. If you had used a def instead, you could hav avoided having to
construct multiple times.
Jul 20 '06 #14
danielx wrote:
(snip)
Python's lambda really can't be as powerful as Lisp's because Python
does not have expressions that do case analysis (this is not lambda's
fault, of course ;). The reason is that you really want to put each
case on its own set of lines. This enhances readability at the expense
of terseness. Since Python's statements are terminated by a newline, it
would be rather awkward to have a kind of expression where good style
calls for it to be spread out accross multiple lines.

You can try to simulate these kinds expressions using into a list or
dictionary, but this becomes rather messy. I think the only way to get
this done properly is to use eval. For example:

def recursiveFuncti on(args):
... # do stuff...
choices = { True:"0", False:"recurisv eFunction(newAr gs)" }
return eval( choices[predicate] )
Why do you want to use eval here ?
The reason that you need eval is that you want to prevent any cases
from being executed until you decide which one you want.
What about:

def recursiveFuncti on(args):
... # do stuff...
... # that defines 'newArgs' and 'predicate' of course ...
return (recursiveFunct ion, lambda x: 0)[predicate](newArgs)

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 20 '06 #15

Bruno Desthuilliers wrote:
danielx wrote:
(snip)
Python's lambda really can't be as powerful as Lisp's because Python
does not have expressions that do case analysis (this is not lambda's
fault, of course ;). The reason is that you really want to put each
case on its own set of lines. This enhances readability at the expense
of terseness. Since Python's statements are terminated by a newline, it
would be rather awkward to have a kind of expression where good style
calls for it to be spread out accross multiple lines.

You can try to simulate these kinds expressions using into a list or
dictionary, but this becomes rather messy. I think the only way to get
this done properly is to use eval. For example:

def recursiveFuncti on(args):
... # do stuff...
choices = { True:"0", False:"recurisv eFunction(newAr gs)" }
return eval( choices[predicate] )

Why do you want to use eval here ?
The reason that you need eval is that you want to prevent any cases
from being executed until you decide which one you want.

What about:

def recursiveFuncti on(args):
... # do stuff...
... # that defines 'newArgs' and 'predicate' of course ...
return (recursiveFunct ion, lambda x: 0)[predicate](newArgs)
Sure, that works, but don't take things so literally. For instance, if
you have a bunch of cases, you might not way to apply the same set of
arguments to all of them.

Also, let's not get distracted from the main point about how doing case
analysis in an expression is ugly, making lambda's weaker in Python
than in the language which inspired them.
>
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 20 '06 #16
danielx wrote:
Bruno Desthuilliers wrote:
>>danielx wrote:
(snip)

>>>Python's lambda really can't be as powerful as Lisp's because Python
does not have expressions that do case analysis (this is not lambda's
fault, of course ;). The reason is that you really want to put each
case on its own set of lines.
An expression can span several lines.
This enhances readability at the expense
>>>of terseness. Since Python's statements are terminated by a newline,
or by a ';'
it
>>>would be rather awkward to have a kind of expression where good style
calls for it to be spread out accross multiple lines.
I must be pretty dumb, but I don't see how this relate to the problem of
case analysis in lambda expressions ?
>>>You can try to simulate these kinds expressions using into a list or
dictionary , but this becomes rather messy. I think the only way to get
this done properly is to use eval. For example:

def recursiveFuncti on(args):
... # do stuff...
choices = { True:"0", False:"recurisv eFunction(newAr gs)" }
return eval( choices[predicate] )

Why do you want to use eval here ?

>>>The reason that you need eval is that you want to prevent any cases
from being executed until you decide which one you want.

What about:

def recursiveFuncti on(args):
... # do stuff...
... # that defines 'newArgs' and 'predicate' of course ...
return (recursiveFunct ion, lambda x: 0)[predicate](newArgs)


Sure, that works, but don't take things so literally.
Sorry for being pragmatic !-)
For instance, if
you have a bunch of cases, you might not way to apply the same set of
arguments to all of them.
return {
'case1' : lambda: someFunc(args1) ,
'case2' : lambda: someFunc(args2) ,
'case3' : lambda: someOtherFunc(a rgs1, arg42),
}.get(predicate , lambda: 0)()

Still no need for eval()...

Now of course there are limits to the exercice, and we're still far away
from ML-like pattern matching or Lisp 'case' forms. As you noted, Python
is a statement-based language, not an expression-based one like Lisp.
This makes a definitive difference.
Also, let's not get distracted from the main point about how doing case
analysis in an expression is ugly,
Ugliness is in the eyes of the beholder <wink>
making lambda's weaker in Python
than in the language which inspired them.
The fact is that Python "lambdas" are *not* Lisp lambdas. Python
"lambdas" are mostly a handy trick to turn a *simple* expression into a
closure - and definitively not a basic building block of the language.

Daniel, I of course do agree that Python lambdas are nothing near Lisp
lambdas - FWIW, Python is not Lisp neither -, but that looks like an
apple and banana comparison to me... IMHO, the most obvious problem with
Python lambdas is the word "lambda" !-)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 21 '06 #17

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

Similar topics

21
2381
by: j_mckitrick | last post by:
Just thought I'd play devil's advocate... I tried wxPython briefly, and it had some nice features. It has a huge list of dependencies. I don't like the fonts (but I'd love to know how to get fixed fonts, or at least anything that looks better on a small laptop screen. TkInter seems much easier to use... less effort to do things.
65
5396
by: perseus | last post by:
I think that everyone who told me that my question is irrelevant, in particular Mr. David White, is being absolutely ridiculous. Obviously, most of you up here behave like the owners of the C++ language. A C++ interface installation IS ABOUT THE C++ LANGUAGE! The language does not possess the ability to handle even simple file directory manipulation. Those wise people that created it did not take care of it. So, BOOST is a portable...
9
3752
by: Dave H | last post by:
Hello, I have a query regarding definition lists. Is it good practice semantically to use the dt and dd elements to mark up questions and answers in a frequently asked questions list, or FAQ? Here is an example of just such a usage: <dl class="faq"> <di>
11
4273
by: Mark Yudkin | last post by:
The documentation is unclear (at least to me) on the permissibility of accessing DB2 (8.1.5) concurrently on and from Windows 2000 / XP / 2003, with separate transactions scope, from separate threads of a multithreaded program using embedded SQL. Since the threads do not need to share transaction scopes, the sqleAttachToCtx family of APIs do not seem to be necessary. <quote> In the default implementation of threaded applications against...
29
3583
by: MP | last post by:
Greets, context: vb6/ado/.mdb/jet 4.0 (no access)/sql beginning learner, first database, planning stages (I think the underlying question here is whether to normalize or not to normalize this one data field - but i'm not sure) :-) Background info:
53
4096
by: Jeff | last post by:
In the function below, can size ever be 0 (zero)? char *clc_strdup(const char * CLC_RESTRICT s) { size_t size; char *p; clc_assert_not_null(clc_strdup, s); size = strlen(s) + 1;
6
1453
by: Bhuwan Bhaskar | last post by:
Hi, I want to know what is anonymas methods and how they can be used. Thanks and regards. Bhuwan
3
1331
by: gnewsgroup | last post by:
I want to get my hands dirty with Linq, so I watched a few videos from www.asp.net, and then turned to http://msdn2.microsoft.com/en-us/library/bb397687.aspx for some introduction about the new lamda feature of C#. In the article linked above, there is an example reproduced here: int numbers = {5,4,1,3,9,8,6,7,2,0 };
5
2327
by: Just_a_fan | last post by:
I tried to put an "on error" statement in a routine and got the message that I cannot user "on error" and a lamda or query expression in the same routine. Help does not list anything useful for explaining a "lamda" expression and so I don't know what one is and I am not doing any database stuff in the entire program. So what does this error message really mean and what can I do to get an On Error into the routine?
0
9687
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
9541
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
10251
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
10225
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
10027
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
9072
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7564
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
5463
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
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.