[Tutor] lambda and map
alan.gauld@bt.com
alan.gauld@bt.com
Sun, 27 May 2001 19:41:49 +0100
> Okay, I am now what I would call competent in Python. But, I keep
> noticing (learning) some new stuff every time I get an email from
> tutor. There is, however, one thing I am not really sure about,
> lambda. I don't quite understand what a lambda does or why
> to use it.
First, I will (as usual? :-) recommend you visit my tutor
and read the Functional Programming advbanced topic. It
explains how lambda works and to some extent why.
http://www.crosswinds.net/~agauld/
Now the short answer:
lambda is just a shortcut for defining a single
line function. It saves us cluttering up our code with lots of little
functions that only get used one.
thus:
double = lambda x : x*2
is identical to:
def double(x): return x*2
But in situations where we need to pass a function object - like map() we
can create the lambda within the map function call instead of defining it as
a function first. Thus
def double(x): return x*2
twos = map(double, range(6))
is the same as but longer than:
twos = map(lambda x: x*2, range(6))
There is also another use, particularly in programming
Tkinter where we use a lambda within a loop to create
the command function for a set of widgets. If the
function has a default parameter. You cant do that
by defining a function because the default parameter
is set when you define it, however using lambda inside
the loop we create a new default each time thru the loop.
(See my hmgui.py code in the Games framework on Useless
Python for an example of this use.)
HTH.
Personal aside to the list...
To be honest, in Python lamda is a bit limited
- essentially to single line expressions.
I'm not sure why we can't do:
>>>modmult = lambda x,y:
result = x * y
if result > 0:
return result
else: return (-1 * result)
>>>modmult(4,3)
12
>>>modmult(4,-3)
12
I know that in this case a def modmult(x,y): would do
the same(*) but given lambda's use of a colon I'd have
thought the extra to allow block defintions would
have been viable.
Alan G.