473,903 Members | 6,365 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

explain this function to me, lambda confusion

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

>>def addn(n):
return lambda x,inc=n: x+inc

>>addn(5)
<function <lambdaat 0x01D81830>
ok? so what do i write to make it actually do something. and is the
inc=n necessary i cant do x+n?
Jun 27 '08 #1
21 1872
and what si the diffrence here:

g = lambda x=5:x*x
g = lambda x:x*x

the first was a mistake to write but it worked
and the x=5 seems to be completely ignored. why? it has no effect at
all?
Jun 27 '08 #2
On 7 Maj, 23:47, globalrev <skanem...@yaho o.sewrote:
and what si the diffrence here:

g = lambda x=5:x*x
g = lambda x:x*x

the first was a mistake to write but it worked
and the x=5 seems to be completely ignored. why? it has no effect at
all?
ah wait now i see it has a default kind of then. g() returns 25 while
g(8) returns 64.
Jun 27 '08 #3
On 7 mai, 23:38, globalrev <skanem...@yaho o.sewrote:
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
It returns a function that accept one argument and return the result
of the addition of this argument with the argument passed to addn.

FWIW, Python's lambda is just a shortcut to create a very simple
function, and the above code is canonically written as:

def makeadder(n):
def adder(x):
return n + x
return adder
if i do addn(5) it returns
(snip)
<function <lambdaat 0x01D81830>

ok? so what do i write to make it actually do something.
add5 = addn(5)
add5(1)
=6
add5(2)
=7

add42 = addn(42)
add42(1)
=43
and is the
inc=n necessary i cant do x+n?
In this case, it's not. This version does exactly the same thing
AFAICT:

def addn(n):
return lambda x: x+n

Jun 27 '08 #4
En Wed, 07 May 2008 18:38:15 -0300, globalrev <sk*******@yaho o.se>
escribió:
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
lambda is just a shortcut for defining a function without a name.
The above code is the same as:

def addn(n):
def inner(x, inc=n):
return x+inc
return inner

It should be clear now that addn returns a function. addn is a "function
factory": builds functions by request. You ask it "give me a function that
adds 5" and addn returns that function.
if i do addn(5) it returns
>>>addn(5)
<function <lambdaat 0x01D81830>
If you try the other version, you would get:

<function inner at 0x00A3B970>

It's the same thing, except that lambda has no name.
ok? so what do i write to make it actually do something.
adder5 = addn(5)
adder5(3)
-8
and is the
inc=n necessary i cant do x+n?
Yes, you can, but there is a subtle difference that's hard to explain, and
in this case it's absolutely irrelevant. Using inc=n "does the right
thing" as it's a bit more efficient too.

--
Gabriel Genellina

Jun 27 '08 #5
On May 8, 7:38 am, globalrev <skanem...@yaho o.sewrote:
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
>def addn(n):

return lambda x,inc=n: x+inc
>addn(5)

<function <lambdaat 0x01D81830>

ok? so what do i write to make it actually do something. and is the
inc=n necessary i cant do x+n?
Here are some notes I have written for our local wiki on lambdas in
python. I hope you will find them illuminating, and I would welcome
any suggestions for improving them.

I have just cut and pasted from our wiki, so the fancy formatting has
been lost.

-----

Python lambdas.

The on-line documentation for python lambdas is not very illuminating.
Here¡¯s my take and my first simple examples.

I would describe a lambda as a parameterised function template. If you
dig, the docs call lambdas anonymous functions not bound to a name.
There is a bit of resemblance to C macros.

Here is a simple lambda that implements an exclusive or:
>>def XOR(x,y) :
return lambda : ( ( x ) and not ( y ) ) or ( not ( x ) and ( y ) )
(Because of the resemblance to C macros, I have been cautious and
written the lambda with lots of parentheses.)

To use this in later code, we define instances of the lambda with
specific function arguments.
>>topping = XOR( cream, icecream)
sauce = XOR( tomato, BBQ )

We now have two ¡°functions¡±, topping() and sauce() which we can use
later to test flags.
>>cream = True
icecream = False
print topping()
True
So in the definition of the XOR lambda, think of x and y as the
parameters of the function template, and XOR as the function name
placeholder.

By putting in specific objects for the parameters (here the boolean
variables cream and icecream for example), we produce a specific
instance of the lambda, topping() which looks like a function with no
arguments.

If we use different objects for the parameters (say tomato and BBQ)
then we get a different function, sauce.

Here is another simple lambda, (template) to set up three new
functions AddOnly, DeleteOnly, and ReplaceOnly.

#--# Lambda function to check that a flag is only on when the other
two are off. #--#
def TFF(x,y,z) :
return lambda : ( ( x ) and not ( y ) and not ( z ) )

AddOnly = TFF( options.AddActi on, options.Replace Action,
options.DeleteA ction )
DeleteOnly = TFF( options.DeleteA ction, options.AddActi on,
options.Replace Action )
ReplaceOnly = TFF( options.Replace Action, options.AddActi on,
options.DeleteA ction )

if( not (DeleteOnly() or AddOnly() or ReplaceOnly() ) ):
print "Error: Exactly one of [ --add | --replace | --delete ]
allowed. "
parser.print_he lp()
exit
More advanced lambdas.

The examples above give function instances that have no arguments,
once the parameters of the lambda are chosen.

For a function template with arguments and parameters, we add the
arguments on the 2nd line. Parameters are in the first line.

The Gaussian distribution is exp(-(x-¥ì)©÷/ 2¥ò©÷ ) / ¡î(4 ¥ð¥ò). While we
can think of this as a function of three variables, we normally view
it as a family of functions of a single variable x, parameterised by ¥ì
and ¥ò. Selecting fixed values for ¥ì and ¥ò gives us a single
distribution for x.
>>import math
def Gaussian( mu, sigma ) :
... return lambda x : math.exp( - (x-mu)**2 / 2 /sigma**2 ) /
math.sqrt (2 * math.pi *sigma **2 )
...
>>>
and here are some instances:
>>Normal = Gaussian (0, 1)
HeightDistr ib = (170, 20)
which we later use as
>>y = Normal( 0.5 )
0.3520653267642 9952
>>x = 192
HeightDistrib (x)
0.0073381331586 869951

I recommend defining the instances of the lambda right after the
lambda. If you define it in code far removed from the definition of
the lambda, it looks like an assignment, so comment it.
Jun 27 '08 #6
On May 8, 10:34 am, andrej.panj...@ climatechange.q ld.gov.au wrote:
>
>HeightDistri b = (170, 20)
That should be
>HeightDistri b = Gaussian(170, 20)
Jun 27 '08 #7

<an************ @climatechange. qld.gov.auwrote in message
news:b2******** *************** ***********@a9g 2000prl.googleg roups.com...

| On May 8, 7:38 am, globalrev <skanem...@yaho o.sewrote:
| I would describe a lambda as a parameterised function template. If you
| dig, the docs call lambdas anonymous functions not bound to a name.

A lambda expression is an abbreviation of a simple def statement:
f = lambda args: expression
def f(args): return expression
have exactly the same effect except that f.func_name will be the less
useful '<lambda>' instead of the more useful 'f'.

| There is a bit of resemblance to C macros.

Macros in C (and, I believe, some places elsewhere) are text-replacement
templates. They are markedly different from function statements. C macros
do not create C functions. Python lambda expression do create Python
function objects. Since C macros are statements, not expressions, and are
introduced by #define, similar to def, one could argue than Python def
statements are more similar to C macros.

| Here is a simple lambda that implements an exclusive or:
|
| >>def XOR(x,y) :
| >> return lambda : ( ( x ) and not ( y ) ) or ( not ( x ) and ( y ) )

def XORY(x,y):
def _xory(): x and not y or not x and y
return _xory

has the same effect. Because lambda expressions define functions, not
macros, there is no need for the protective parentheses that macros need.

Here is another simple lambda, (template) to set up three new
| functions AddOnly, DeleteOnly, and ReplaceOnly.
|
| #--# Lambda function to check that a flag is only on when the other
| two are off. #--#
| def TFF(x,y,z) :
| return lambda : ( ( x ) and not ( y ) and not ( z ) )

def TFF(x,y,z):
def _tff(x,y,z): return ( ( x ) and not ( y ) and not ( z ) )
return _tff

Same result (except for a real name in tracebacks), same usage.

| >>import math
| >>def Gaussian( mu, sigma ) :
| ... return lambda x : math.exp( - (x-mu)**2 / 2 /sigma**2 ) /
| math.sqrt (2 * math.pi *sigma **2 )

def Gaussian(mu, sigma):
def _gaussian(x): return math.exp( - (x-mu)**2 / 2 /sigma**2 ) /
math.sqrt (2 * math.pi *sigma **2 )
return _gaussian

Again, giving the returned function a name will help a bit if it raises an
exception, which is definitely possible here.

Lambda expressions are an occasional convienience, not a requirement.
Anyone who is confused by what they do should use an equivalent def
instead.

Terry Jan Reedy

Jun 27 '08 #8
an************@ climatechange.q ld.gov.au wrote:
Here is a simple lambda that implements an exclusive or:
>>>def XOR(x,y) :
return lambda : ( ( x ) and not ( y ) ) or ( not ( x ) and ( y )
)
>
(Because of the resemblance to C macros, I have been cautious and
written the lambda with lots of parentheses.)

To use this in later code, we define instances of the lambda with
specific function arguments.
>>>topping = XOR( cream, icecream)
sauce = XOR( tomato, BBQ )


We now have two *øfunctions*ñ, topping() and sauce() which we can use
later to test flags.
>>>cream = True
icecream = False
print topping()
True
No, no, no, no, no!

You have got it entirely wrong here. Your XOR function simply returns a
function which gives you the result of xoring the parameters AT THE TIME
WHEN YOU ORIGINALLY CREATED IT. I'm guessing that you had already set
cream and icecream (otherwise the call to XOR would have thrown an
exception) and at leas one was true. Try setting them both False at the
beginning:
>>cream = False
icecream = False
topping = XOR( cream, icecream)
cream = True
icecream = False
print topping()
False

Using a lambda was a completely pointless exercise here, you could have
just returned the result directly:
>>def XOR(x,y):
return x^y
>>topping = XOR(cream, icecream)
print topping
True

Same thing for your TFF function:

def TFF(x,y,z) :
return x and not y and not z

AddOnly = TFF( options.AddActi on, options.Replace Action,
options.DeleteA ction )
DeleteOnly = TFF( options.DeleteA ction, options.AddActi on,
options.Replace Action )
ReplaceOnly = TFF( options.Replace Action, options.AddActi on,
options.DeleteA ction )

if not (DeleteOnly or AddOnly or ReplaceOnly):
print "Error: Exactly one of [ --add | --replace | --delete ]
allowed. "
parser.print_he lp()
exit

which boils down to:

if (options.AddAct ion + options.Replace Action +
options.DeleteA ction) != 1:
print "Error: ..."
Jun 27 '08 #9
On May 8, 6:11 pm, Duncan Booth <duncan.bo...@i nvalid.invalidw rote:
>
No, no, no, no, no!
Geez. Go easy.
You have got it entirely wrong here. Your XOR function simply returns a
function which gives you the result of xoring the parameters AT THE TIME
WHEN YOU ORIGINALLY CREATED IT. I'm guessing that you had already set
cream and icecream (otherwise the call to XOR would have thrown an
exception) and at leas one was true. Try setting them both False at the
beginning:
>cream = False
icecream = False
topping = XOR( cream, icecream)
cream = True
icecream = False
print topping()

False
Ok. I understand this better now. I did say I found the documentation
rather terse on this.
Using a lambda was a completely pointless exercise here, you could have
just returned the result directly:

If I try out a new language, I try to exercise those parts of the
language that are new to me. Now I saw lambdas, an interesting
structure I hadn't seen before. So I tried them out. I get to learn a
little at the same time as scripting. That was the "point". I only
get to optimise my use of a language by trying out various corners of
it.
def TFF(x,y,z) :
return x and not y and not z

AddOnly = TFF( options.AddActi on, options.Replace Action,
options.DeleteA ction )
DeleteOnly = TFF( options.DeleteA ction, options.AddActi on,
options.Replace Action )
ReplaceOnly = TFF( options.Replace Action, options.AddActi on,
options.DeleteA ction )

if not (DeleteOnly or AddOnly or ReplaceOnly):
print "Error: Exactly one of [ --add | --replace | --delete ]
allowed. "
parser.print_he lp()
exit

which boils down to:

if (options.AddAct ion + options.Replace Action +
options.DeleteA ction) != 1:
print "Error: ..."
Indeed, there are many ways this could be done. Some are more
concise, some are more efficient. As I said, I did it the way I did
it to try out lambdas. Your way achieves the result, rather elegantly
I think, but teaches me nothing about using lambdas.

Pardon my tetchiness, but it is a little hard to receive such blunt
and inflexible replies to my posts.

Both the responses offer lambda free alternatives. That's fine, and
given the terse documentation and problems that I had understanding
them, I would agree. So what applications are lambdas suited to? I
think the parameterised function model is one.
What else?
Jun 27 '08 #10

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

Similar topics

8
2525
by: Rico Huijbers | last post by:
Hello, I'd like to know if it's possible to curry a function in PHP? That is, is there some built-in mechanism for it, or is it possible to create a function that does the currying? I've tried something myself, and come up with the following: ---
5
2005
by: Elaine Jackson | last post by:
Suppose one of the arguments of a function f_1 is another function f_2. Can f_1 access the number of arguments taken by f_2? (I'm writing a little script to automate the construction of logical truth-tables.) Thanks. Peace
9
2766
by: Lenard Lindstrom | last post by:
I was wondering if anyone has suggested having Python determine a method's kind from its first parameter. 'self' is a de facto reserved word; 'cls' is a good indicator of a class method ( __new__ is a special case ). The closest to this I could find was the 2002-12-04 posting 'metaclasses and static methods' by Michele Simionato. The posting's example metaclass uses the method's name. I present my own example of automatic method kind...
6
3374
by: Alan G Isaac | last post by:
Given a list of functions, it seems there must be a Pythonic approach to composition. Something like def compose(fns): return lambda x: reduce(lambda f,g: f(g),fns)(x) This will not work because the argument 'x' is not "inside". What is the proper formulation? Thanks, Alan Isaac
8
1720
by: Uwe Mayer | last post by:
Is it possible to specify anonymous functions, something like: >>> f = {print "hello world"} >>> f() hello world in Pyton? Lambda expressions don't work here.
4
2507
by: Tony Lownds | last post by:
(Note: PEPs in the 3xxx number range are intended for Python 3000) PEP: 3107 Title: Function Annotations Version: $Revision: 53169 $ Last-Modified: $Date: 2006-12-27 20:59:16 -0800 (Wed, 27 Dec 2006) $ Author: Collin Winter <collinw@gmail.com>, Tony Lownds <tony@lownds.com> Status: Draft Type: Standards Track
4
2497
by: silverburgh.meryl | last post by:
I have code which uses Boost lambda in a template like this: using namespace boost::lambda; template<class T> bool lessThanXY( T& src, T& dest ) { return (src.getY() < dest.getY()); } template<class T1, class T2>
17
8112
by: DanielJohnson | last post by:
how to use the combination function in python ? For example 9 choose 2 (written as 9C2) = 9!/7!*2!=36 Please help, I couldnt find the function through help.
9
4734
by: Andrew Poulos | last post by:
Say I have this: var foo = function(x, y) { return x + y; }; var bar = function(fname, param1, param2) { /* * how do I call the function "foo" * and pass parameters to it?
0
9999
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
10875
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
10986
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
10501
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
9685
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
8049
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
6093
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4727
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
3324
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.