lambda

Laszlo Nagy gandalf at designaproduct.biz
Thu Aug 24 13:43:04 EDT 2006


> what is a lambda expression?
labmda is a reserved word and AFAIK it is an operatior.
By using lamba, you can create an anonymous function. That is, a 
function without name.

For example, doing

def create_adder(amount):
    def adder(x):
       return x + amount
    return adder


is equvalent to:

def create_adder(amount):
   return lambda x : x + amount

In the former case:

 >>> f1 = create_adder(4)
 >>>f1
<function adder at 0x00BE6930>
 >>> f1(2)
6

In the later case:

 >>> f2 = create_adder(4)
 >>> f2
<function <lambda> at 0x00BE66F0>
 >>> f2(2)
6

For example, if you want create a new list by adding 4 to the elements 
of another list:

 >>> another = [1,2,3,4,5]
 >>> newlist = map( lambda x: x+4 , another)
 >>> newlist
[5, 6, 7, 8, 9]

Best,

   Laszlo




More information about the Python-list mailing list