faqts : Computers : Programming : Languages : Python : Language and Syntax

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

21 of 26 people (81%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

What is lambda?

Jul 1st, 2000 20:12
unknown unknown, Warren Postma, david_ullrich


1) Meta-Answer: Read the FAQ and Manual sections.

2) Instant Gratification Answer

Here's a standard function definition:

def func(x):
    return x *2

Here's a way to write the same thing, in effect, but using Lambda:

func = lambda (x): x * 2

While that example isn't useful, it gives you the idea.  Think of lambda 
as a way to generate a function and return that function as an object, 
without having to give it a name. I primarily use it to pass an 
algorithm or expression as a parameter to a function, or other places 
where I want to pass code in a variable instead of passing a reference 
to a method containing that code.

------------

What it does is allow you to construct "anonymous functions".

   Oops, not my own words. The syntax

lambda x: [expression in x]

is itself an expression - the _value_ of the expression "lambda x: 
[expression in x]" is a function which returns [expression in x] when 
passed x. For example "lambda x: x+x" is a function that returns x+x; 
saying

f = lambda x: x+x

has the same effect as saying

def f(x):
  return x + x

But you don't usually use it that way - people use lambda when they want 
to pass a function to some routine without having to make up a name for 
the function. For example map takes a function as a parameter; saying

print map(lambda x: x+x, [1,2,3])

is the same as saying

def f(x):
  return x + x

print map(f, [1,2,3]])

You should note there's varying opinions on whether lambda is a good 
thing - if you're a beginner at programming as well as with Python it's 
not the first thing you should worry about.