Why use lambda functions?

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


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.


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.


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 ;)