tags:

views:

338

answers:

4

Can you give an example and other examples that show when and when not to use Lambda? My book gives me examples, but they're confusing.

+3  A: 

A simple Google search for Python Lambda Example is all you need. There are loads of simple examples.

http://www.secnetix.de/olli/Python/lambda%5Ffunctions.hawk

Andrew Johnson
http://meta.stackoverflow.com/questions/26100/some-people-just-do-not-know-how-to-search suggests that the consensus on easy "Google-able" questions is to _go ahead and answer them_
Chris Lutz
I linked him the exact answer. It both explains the difference between lambdas and regular functions, and it gives a series of simple examples. I'm not going to cut and paste the article here or re-invent the wheel.
Andrew Johnson
And one day, that site will go down because the admins gave up and didn't renew their domain name. Or the site will change and that page will be deleted, or will reorganize and it'll be at a different URL. And where will your answer be then?
Chris Lutz
+2  A: 

I do not know which book you are using, but Dive into Python has a section which I think is informative.

Sinan Ünür
+18  A: 

Lambda, which originated from Lambda Calculus and (AFAIK) was first implemented in Lisp, is basically an anonymous function - a function which doesn't have a name, and is used in-line, in other words you can assign an identifier to a lambda function in a single expression as such:

>>> addTwo = lambda x: x+2
>>> addTwo(2)
4

This assigns addTwo to the anonymous function, which accepts 1 argument x, and in the function body it adds 2 to x, it returns the last value of the last expression in the function body so there's no return keyword.

The code above is roughly equivalent to:

>>> def addTwo(x):
...     return x+2
... 
>>> addTwo(2)
4

Except you're not using a function definition, you're assigning an identifier to the lambda.

The best place to use them is when you don't really want to define a function with a name, possibly because that function will only be used one time and not numerous times, in which case you would be better off with a function definition.

Example of a hash tree using lambdas:

>>> mapTree = {
...     'number': lambda x: x**x,
...     'string': lambda x: x[1:]
... }
>>> otype = 'number'
>>> mapTree[otype](2)
4
>>> otype = 'string'
>>> mapTree[otype]('foo')
'oo'

In this example I don't really want to define a name to either of those functions because I'll only use them within the hash, therefore I'll use lambdas.

meder
Just one tiny little nitpick on an otherwise great answer: lambda does not original from Lisp, but rather from lambda calculus.
phoebus
ah yes, my mistake for using originated - I made some edits. Anything else I should add/modify?
meder
+1 Wonderful answer, consider changing the name `type` in the dict example.. as it is a builtin...
Shrikant Sharat
good catch! done.
meder
Good answer, but I would suggest replacing the example with something that's easier to understand, and a bit more standard. Something like using lambda in a map (map(lambda x: x * 2, l)).
Edan Maor
+1  A: 

Use of lambda is sort of a style thing. When you can get away with a very simple function, and usually where you are just storing it somewhere (in a list of functions perhaps, or in a GUI toolkit data structure, etc.) people feel lambda reduces clutter in their code.

In Python it is only possible to make a lambda that returns a single expression, and the lambda cannot span multiple lines (unless you join the multiple lines by using the backslash-at-the-end-of-a-line trick). People have requested that Python add improvements for lambda, but it hasn't happened. As I understand it, the changes to make lambda able to write any function would significantly complicate the parsing code in Python. And, since we already have def to define a function, the gain is not considered worth the complication. So there are some cases where you might wish to use lambda where it is not possible. In that case, you can just use a def:

object1.register_callback_function(lambda x: x.foo() > 3)

def fn(x):
    if x.foo() > 3:
        x.recalibrate()
        return x.value() > 9
    elif x.bar() > 3:
        x.do_something_else()
        return x.other_value < 0
    else:
        x.whatever()
        return True

object2.register_callback_function(fn)
del(fn)

The first callback function was simple and a lambda sufficed. For the second one, it is simply not possible to use a lambda. We achieve the same effect by using def and making a function object that is bound to the name fn, and then passing fn to register_callback_function(). Then, just to show we can, we call del() on the name fn to unbind it. Now the name fn no longer is bound with any object, but register_callback_function() still has a reference to the function object so the function object lives on.

steveha