Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use lambda functions?

Tags:

python

lambda

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

like image 633
NoMoreZealots Avatar asked Jul 15 '10 19:07

NoMoreZealots


People also ask

Why do we use lambda function in Python?

We use lambda functions when we require a nameless function for a short period of time. In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter() , map() etc.

Why do we use AWS Lambda?

AWS Lambda lets you run code without provisioning or managing servers. You pay only for the compute time you consume - there is no charge when your code is not running. With Lambda, you can run code for virtually any type of application or backend service - all with zero administration.


2 Answers

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

like image 51
JAB Avatar answered Oct 13 '22 06:10

JAB


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.

like image 29
Donald Miner Avatar answered Oct 13 '22 04:10

Donald Miner