[Tutor] Lambda

Glen Wheeler wheelege@hotmail.com
Tue, 5 Feb 2002 17:12:27 +1100


  Hi Greg,

  Sure thing.  I myself really like lambdas...here is not one line, but I
hope it helps shed some light -

>>> def multiply(a,b):
...  return a*b
...
>>> for i in range(5):
...  print multiply(i,2)
...
0
2
4
6
8

  That should be easy to understand, although you may think it a little
weird that I wrote multiply(i,2) instead of i*2.  But what this does is
applies the function multiply (with the second parameter as 2) over the
sequence range(5) - obviously doubling every number in the sequence.  Here
is the same thing but with a lambda -

>>> for i in range(5):
...  print (lambda x,y:x*y)(i,2)
...
0
2
4
6
8

  The whole function object is contained in (lambda x,y:x*y).  This is
horribly inefficient, but still it's a learning exercise.  Here is something
similar using a very cool function called map -

>>> map(lambda x:x*2, range(5))
[0, 2, 4, 6, 8]

  Try typing that into the interactive interpreter.  What that line says is
'apply the function 'lambda x:x*2' to the sequence 'range(5)'.  All that
means is double each element.  Donb't worry if you don't get the map - that
was just a little extra bit :)

  Good luck!
  Glen


----- Original Message -----
From: "Greg Guest" <greg.guest@3web.net>
To: <tutor@python.org>
Sent: Tuesday, February 05, 2002 1:28 PM
Subject: [Tutor] Lambda


Hi everyone,

Emboldened by Jeff Shannon's remark of a couple of weeks ago that he finds
lambdas counterintuitive, I ask my first question to the tutor.

I not only find them counterintuitive, but can't even figure out what they
do in a line of code.  I would be grateful if someone could translate a line
using lambda into one that doesn't.

I've been reading the tutor for a couple of months now, and find it a
wonderful place.  The threads on Classes have helped me a lot.

TIA
Greg Guest

A Palindrome:
Straw? No, too stupid a fad.  I put soot on warts.




__________________________________________________________
Get Premium UNLIMITED Internet Access across CANADA for
JUST $9.95/MONTH at http://www.get3web.com/?mkid=t123