Why use lambda functions?

PythonLambda

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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.

Solution 3 - Python

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.

Solution 4 - Python

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

Solution 5 - Python

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

Solution 6 - Python

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.

Solution 7 - Python

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."

Solution 8 - Python

It is definitely true that abusing lambda functions often leads to bad and hard-to-read code. On the other hand, when used accurately, it does the opposite. There are already great answers in this thread, but one example I have come across is:

def power(n):
    return lambda x: x**n

square = power(2)
cubic = power(3)
quadruple = power(4)

print(square(10)) # 100
print(cubic(10)) # 1000
print(quadruple(10)) # 10000

This simplified case could be rewritten in many other ways without the use of lambda. Still, one can infer how lambda functions can increase readability and code reuse in perhaps more complex cases and functions with this example.

Solution 9 - Python

Lambdas are anonymous functions (function with no name) that can be assigned to a variable or that can be passed as an argument to another function. The usefulness of lambda will be realized when you need a small piece of function that will be run one in a while or just once. Instead of writing the function in global scope or including it as part of your main program you can toss around few lines of code when needed to a variable or another function. Also when you pass the function as an argument to another function during the function call you can change the argument (the anonymous function) making the function itself dynamic. Suppose if the anonymous function uses variables outside its scope it is called closure. This is useful in callback functions.

Solution 10 - Python

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.

Solution 11 - Python

Lambdas are objects, not methods, and they cannot be invoked in the same way that methods are. for e.g

succ = ->(x){ x+1 }

succ mow holds a Proc object, which we can use like any other:

succ.call(2)

gives us an output = 3

Solution 12 - Python

I want to point out one situation other than list-processing where the lambda functions seems the best choice:

from tkinter import *
from tkinter import ttk        
def callback(arg):
    print(arg)
    pass
root = Tk()
ttk.Button(root, text = 'Button1', command = lambda: callback('Button 1 clicked')).pack()
root.mainloop()

And if we drop lambda function here, the callback may only execute the callback once.

ttk.Button(root, text = 'Button1', command = callback('Button1 clicked')).pack()

Solution 13 - Python

Another point is that python does not have switch statements. Combining lambdas with dicts can be an effective alternative. e.g.:

switch = {
 '1': lambda x: x+1, 
 '2': lambda x: x+2,
 '3': lambda x: x+3
}

x = starting_val
ans = expression
new_ans = switch[ans](x)

Solution 14 - Python

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.

Solution 15 - Python

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.

Solution 16 - Python

you master lambda, you master shortcuts in python.Here is why:

data=[(lambda x:x.text)(x.extract())  for x in soup.findAll('p') ]
                  ^1           ^2         ^3           ^4

here we can see 4 parts of the list comprehension:

  • 1: i finally want this
  • 2: x.extract will perform some operation on x, here it pop the element from soup
  • 3: x is the list iterable which is passed to the input of lambda at 2 along with extract operation
  • 4: some arbitary list

> i had found no other way to use 2 statements in lambda, but with this > kind of pipe-lining we can exploit the infinite potential of lambda.

Edit: as pointed out in the comments, by juanpa, its completely fine to use x.extract().text but the point was explaining the use of lambda pipe, ie passing the output of lambda1 as input to lambda2. via (lambda1 y:g(x))(lambda2 x:f(x))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNoMoreZealotsView Question on Stackoverflow
Solution 1 - PythonJABView Answer on Stackoverflow
Solution 2 - PythonDonald MinerView Answer on Stackoverflow
Solution 3 - PythonDavidView Answer on Stackoverflow
Solution 4 - PythonWayne WernerView Answer on Stackoverflow
Solution 5 - PythonPiotr KalinowskiView Answer on Stackoverflow
Solution 6 - Pythonjust somebodyView Answer on Stackoverflow
Solution 7 - Pythonuser297250View Answer on Stackoverflow
Solution 8 - PythonUzay MacarView Answer on Stackoverflow
Solution 9 - PythonAnupama V IyengarView Answer on Stackoverflow
Solution 10 - PythonTony VeijalainenView Answer on Stackoverflow
Solution 11 - PythonAkash SotiView Answer on Stackoverflow
Solution 12 - PythonHenry.LView Answer on Stackoverflow
Solution 13 - PythonzzuView Answer on Stackoverflow
Solution 14 - PythonabbotView Answer on Stackoverflow
Solution 15 - PythonphkahlerView Answer on Stackoverflow
Solution 16 - Pythonnikhil swamiView Answer on Stackoverflow