Why to use Lambda to send Function as Argument to Another Function
<p>While digging into <code>lambda</code> I defined this code below:</p>

<pre><code>def f2(number, lambda_function):
    return lambda_function(number)

def f1(number):
    return f2(number, lambda x: x*2) 

number = 2
print f1(number)
</code></pre>

<p>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:</p>

<pre><code>def f1(number):
    return number*2

number = 2
print f1(number)
</code></pre>

<p>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 <code>lambda</code> and the function programming tricks. Can the code above be modified to illustrate a situation when a task could not be completed without using <code>lambda</code>? What is the purpose of <code>lambda</code> in Python? Can you show me the example of where <code>lambda</code> really "shines"? May be an example where the use of <code>lambda</code> simplified the code?</p>

<p><a href="https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions" rel="nofollow"><code>lambda</code></a> 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:</p>

<pre><code>&gt;&gt;&gt; my_list = [(1, 3) , (4, 8), (2, 3), (1, 6)]
&gt;&gt;&gt; my_list.sort(key=lambda x: (x[0], -x[1]))
&gt;&gt;&gt; my_list
[(1, 6), (1, 3), (2, 3), (4, 8)]
</code></pre>

<p>Here, I am sorting <code>my_list</code> in increasing order of index <code>0</code> and then decreasing order of index <code>1</code>. But <code>list.sort()</code> accepts value of <code>key</code> as function. Instead of defining the function and then pass that function over here, it is cleaner to make a <code>lambda</code> call within it. </p>

<p>Since these can be written as an expression, they are termed as <a href="https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions" rel="nofollow"><code>Lambda Expression</code></a> in document, instead of <em>Lambda Function</em>.</p>

<p>Also read: <a href="http://stackoverflow.com/questions/890128/why-are-python-lambdas-useful">Why are Python lambdas useful?</a></p>

<p>In the example that you have given, I do not think that using <code>lambda</code> there is any useful.</p>

python