Reputation: 19329
While digging into lambda
I defined this code below:
def f2(number, lambda_function):
return lambda_function(number)
def f1(number):
return f2(number, lambda x: x*2)
number = 2
print f1(number)
While I do agree the code like this looks pretty cool I wonder why wouldn't I just put it down using a more traditional approach, like so:
def f1(number):
return number*2
number = 2
print f1(number)
I understand that some languages rely on the functional programming more than Python. But in Python I end up with less lines and more readable friendly code if I just avoid lambda
and the function programming tricks. Can the code above be modified to illustrate a situation when a task could not be completed without using lambda
? What is the purpose of lambda
in Python? Can you show me the example of where lambda
really "shines"? May be an example where the use of lambda
simplified the code?
Upvotes: 1
Views: 40
Reputation: 48067
lambda
functions work like normal function but are used in cases where they will be executed just once. Then, why to create the message body and define the function? For example, sorting the list of tuples:
>>> my_list = [(1, 3) , (4, 8), (2, 3), (1, 6)]
>>> my_list.sort(key=lambda x: (x[0], -x[1]))
>>> my_list
[(1, 6), (1, 3), (2, 3), (4, 8)]
Here, I am sorting my_list
in increasing order of index 0
and then decreasing order of index 1
. But list.sort()
accepts value of key
as function. Instead of defining the function and then pass that function over here, it is cleaner to make a lambda
call within it.
Since these can be written as an expression, they are termed as Lambda Expression
in document, instead of Lambda Function.
Also read: Why are Python lambdas useful?
In the example that you have given, I do not think that using lambda
there is any useful.
Upvotes: 3