views:

584

answers:

11

I can find lots of stuff showing me what a lambda function is, and how the syntax works and what not. But other than the "coolness factor" (I can make a function in middle a call to another function, neat!) I haven't seen something that's overwelmingly compelling to say why I really need/want to use them.

It seems to be more of a stylistic or structual choice in most examples I've seen. And kinda breaks the "Only one correct way to do something" in python rule. How does it make my programs, more correct, more reliable, faster, or easier to understand? (Most coding standards I've seen tend to tell you to avoid overly complex statements on a single line. If it makes it easier to read break it up.)

+4  A: 

For me it's a matter of the expressiveness of the code. When writing code that people will have to support, that code should tell a story in as concise and easy to understand manner as possible. Sometimes the lambda expression is more complicated, other times it more directly tells what that line or block of code is doing. Use judgment when writing.

Think of it like structuring a sentence. What are the important parts (nouns and verbs vs. objects and methods, etc.) and how should they be ordered for that line or block of code to convey what it's doing intuitively.

David
+8  A: 

Here's a good example:

def key(x):
    return x[1]

a = [(1, 2), (3, 1), (5, 10), (11, -3)]
a.sort(key=key)

versus

a = [(1, 2), (3, 1), (5, 10), (11, -3)]
a.sort(key=lambda x: x[1])

From another angle: Lambda expressions are also known as "anonymous functions", and are very useful in certain programming paradigms, particularly functional programming, which lambda calculus provided the inspiration for.

http://en.wikipedia.org/wiki/Lambda_calculus

JAB
unrelated: you could use `operator.itemgetter(1)` instead of `lambda x: x[1]`.
J.F. Sebastian
sort() has supported `key` since 2.4
Amber
@J.F. Sebastian: Though would require you to `import operator` first. @Amber: Thanks; I couldn't remember off the top of my head so just erred on the side of caution.
JAB
@J.F. Sebastian, yes, "operator.itemgetter" ,and hundreds of other short functions one would have to know by heart, each to one specific use -- or use lambda, where one can create a generic expression in place, without having to recall exactly which short function does that one job. _NOT_ using operator.itemgetter seems to justify lambda pretty well, as the OP calls for.
jsbueno
The functions in `operator` are literally a hundred times faster than their lambda counterpart.
THC4k
@THC4k: WOW that's a pretty damn good reason NOT to use lambda functions in this case!
NoMoreZealots
@NoMore: Until you get to some more complicated things e.g. `lambda x: x[0]**2 + x[1]**2`
KennyTM
@KennyTM: Or `lambda x: math.sqrt(x[0]**2 + x[1]**2)` (Though if `x` is of a custom class, you could simply define the `__abs__` method of the class such that it would do that when you use the `abs` function, in which case the key would be `abs`.)
JAB
@NoMore: The performance difference is an implementation artifact of CPython rather than being intrinsic to lambda functions or functions in general.
Roger Pate
+1  A: 

In some cases it is much more clear to express something simple as a lambda. Consider regular sorting vs. reverse sorting for example:

some_list = [2, 1, 3]
print sorted(some_list)
print sorted(some_list, lambda a, b: -cmp(a, b))

For the latter case writing a separate full-fledged function just to return a -cmp(a, b) would create more misunderstanding then a lambda.

abbot
unrelated: you could use `sorted(..., reverse=True)` instead of `sorted(..., lambda a,b: cmp(b,a))`
J.F. Sebastian
+3  A: 

The syntax is more concise in certain situations, mostly when dealing with map et al.

map(lambda x: x * 2, [1,2,3,4])

seems better to me than:

def double(x):
    return x * 2

map(double, [1,2,3,4])

I think the lambda is a better choice in this situation because the def double seems almost disconnected from the map that is using it. Plus, I guess it has the added benefit that the function gets thrown away when you are done.

There is one downside to lambda which limits its usefulness in Python, in my opinion: lambdas can have only one expression (i.e., you can't have multiple lines). It just can't work in a language that forces whitespace.

Plus, whenever I use lambda I feel awesome.

orangeoctopus
list comprehension might be more suitable in this case `[x*2 for x in [1,2,3,4]]`.
J.F. Sebastian
I don't know python (although it's definitely high on my to-learn list), so I'm wondering... is there really a good reason multiple lines aren't allowed for a lambda-expression? Why can't the body of the lambda-expression just be one tab further to the right or something?
Cam
@incrediman: if you're writing multiple lines of lambda, the idea is that you might be better off with a 'proper' function
MikeD
Guido's blog post about multi-line lambdas, and other things: http://www.artima.com/weblogs/viewpost.jsp?thread=147358
orangeoctopus
@incrediman - at that point there is no difference between a lambda and a function - a function is still an object that can be referred to by name, having a multi-line lambda would be a def.
Matthew J Morrison
I don't *know* but I would bet to discourage a more liberal use of lambdas and/or because it would be a pain to parse.
Wayne Werner
`map((2).__mul__, [1,2,3,4])`.
KennyTM
+3  A: 

Yes, you're right — it is a structural choice. It probably does not make your programs more correct by just using lambda expressions. Nor does it make them more reliable, and this has nothing to do with speed.

It is only about flexibility and the power of expression. Like list comprehension. You can do most of that defining named functions (possibly polluting namespace, but that's again purely stylistic issue).

It can aid to readability by the fact, that you do not have to define a separate named function, that someone else will have to find, read and understand that all it does is to call a method blah() on its argument.

It may be much more interesting when you use it to write functions that create and return other functions, where what exactly those functions do, depends on their arguments. This may be a very concise and readable way of parameterizing your code behaviour. You can just express more interesting ideas.

But that is still a structural choice. You can do that otherwise. But the same goes for object oriented programming ;)

Piotr Kalinowski
+2  A: 

One use of lambda function which I have learned, and where is not other good alternative or at least looks for me best is as default action in function parameter by

parameter=lambda x: x

This returns the value without change, but you can supply one function optionally to perform a transformation or action (like printing the answer, not only returning)

Also often it is useful to use in sorting as key:

key=lambda x: x[field]

The effect is to sort by fieldth (zero based remember) element of each item in sequence. For reversing you do not need lambda as it is clearer to use

reverse=True

Often it is almost as easy to do new real function and use that instead of lambda. If people has studied much Lisp or other functional programming, they also have natural tendency to use lambda function as in Lisp the function definitions are handled by lambda calculus.

Tony Veijalainen
+2  A: 

Lambda functions are most useful in things like callback functions, or places in which you need a throwaway function. JAB's example is perfect - It would be better accompanied by the keyword argument key, but it still provides useful information.

When

def key(x):
    return x[1]

appears 300 lines away from

[(1,2), (3,1), (5,10), (11,-3)].sort(key)

what does key do? There's really no indication. You might have some sort of guess, especially if you're familiar with the function, but usually it requires going back to look. OTOH,

[(1,2), (3,1), (5,10), (11,-3)].sort(lambda x: x[1])

tells you a lot more.

  1. Sort takes a function as an argument
  2. That function takes 1 parameter (and "returns" a result)
  3. I'm trying to sort this list by the 2nd value of each of the elements of the list
  4. (If the list were a variable so you couldn't see the values) this logic expects the list to have at least 2 elements in it.

There's probably some more information, but already that's a tremendous amount that you get just by using an anonymous lambda function instead of a named function.

Plus it doesn't pollute your namespace ;)

Wayne Werner
My initial example wasn't quite perfect, as in Python 3 you have to use the key as a keyword argument (resulting in a TypeError being raised if you leave `key=` out). I also forgot that `sort`, which does an in-place sort, doesn't actually return the object it sorts, so you have to use it on a mutable sequence that's already been assigned to a variable.
JAB
A: 

Lambdas allow you to create functions on the fly. Most of the examples I've seen don't do much more than create a function with parameters passed at the time of creation rather than execution. Or they simplify the code by not requiring a formal declaration of the function ahead of use.

A more interesting use would be to dynamically construct a python function to evaluate a mathematical expression that isn't known until run time (user input). Once created, that function can be called repeatedly with different arguments to evaluate the expression (say you wanted to plot it). That may even be a poor example given eval(). This type of use is where the "real" power is - in dynamically creating more complex code, rather than the simple examples you often see which are not much more than nice (source) code size reductions.

phkahler
Lambdas do not allow you to do anything that a normal function definition cannot do equally well. As the other answers say you might prefer a lambda because it makes the code clearer, but an ordinary 'def' is exactly as dynamic as a lambda.
Duncan
No sir, it is not the same. You can define a function to compute x+1, or you can also use a lambda to create a function to compute x+n and pass 1 in for n. You can also use the same lambda to create a bunch of funtions that return x plus different values. The point is that part the some of the function is determined at run time in a way that can't be done with a normal def. Everyone seems to think it's a nice shorthand, when it really can do more.
phkahler
A: 

I think that good example of using "lambda" expression is binding arguments to functions ie.:

def foo(a,b):
    pass

bar = lambda x: foo(5,x)
Tomasz Wysocki
Using `functools.partial()` is probably clearer than `lambda`
blokeley
And you could chain it for functions with long argument lists as a form of currying, too. (Though blokeley is correct about `partial()`.)
JAB
A: 

Ignore for a moment the detail that it's specifically anonymous functions we're talking about. functions, including anonymous ones, are assignable quantities (almost, but not really, values) in Python. an expression like

map(lambda y: y * -1, range(0, 10))

explicitly mentions four anonymous quantities: -1, 0, 10 and the result of the lambda operator, plus the implied result of the map call. it's possible to create values of anonymous types in some languages. so ignore the superficial difference between functions and numbers. the question when to use an anonymous function as opposed to a named one is similar to a question of when to put a naked number literal in the code and when to declare a TIMES_I_WISHED_I_HAD_A_PONY or BUFFER_SIZE beforehand. there are times when it's appropriate to use a (numeric, string or function) literal, and there are times when it's more appropriate to name such a thing and refer to it through its name.

see eg. Allen Holub's provocative, thought-or-anger-provoking book on Design Patterns in Java; he uses anonymous classes quite a bit.

just somebody
A: 

Lambda, while useful in certain situations, has a large potential for abuse. lambda's almost always make code more difficult to read. And while it might feel satisfying to fit all your code onto a single line, it will suck for the next person who has to read your code.

Direct from PEP8

"One of Guido's key insights is that code is read much more often than it is written."

Brendan Abel