avatarCoucou Camille

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3690

Abstract

format as <code>filter</code> and is used to perform a <b>uniform operation for all elements</b> in a sequence:</p><div id="fa2b"><pre><span class="hljs-attr">letters</span> = [<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>, <span class="hljs-string">"d"</span>, <span class="hljs-string">"e"</span>, <span class="hljs-string">"f"</span>, <span class="hljs-string">"g"</span>]</pre></div><div id="eb85"><pre>letters_upper_case = list(<span class="hljs-name">map</span>(<span class="hljs-name">lambda</span> x: x.upper(), letters))</pre></div><div id="0df5"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(letters_upper_case)</span></span> >>> <span class="hljs-selector-attr">[<span class="hljs-string">'A'</span>, <span class="hljs-string">'B'</span>, <span class="hljs-string">'C'</span>, <span class="hljs-string">'D'</span>, <span class="hljs-string">'E'</span>, <span class="hljs-string">'F'</span>, <span class="hljs-string">'G'</span>]</span></pre></div><h2 id="4661">3. Reduce</h2><p id="02a7"><b>Syntax</b>: <code>reduce(function, sequence)</code></p><p id="cae9">The <code>reduce</code> function, like <code>map</code>, is also used to perform an operation <code>function</code> on each element in the <code>sequence</code>. However, it works a bit differently in that the operation is <b>performed among the elements</b>, rather than performed on each element separately.</p><p id="62ba">For example, <code>map</code> is used if you wish to double each element, but <code>reduce</code> is used if you want to get the sum of all elements in the sequence.</p><div id="7039"><pre><span class="hljs-attr">lst</span> = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>] <span class="hljs-attr">doubles</span> = list(map(lambda x: x*<span class="hljs-number">2</span>, lst))</pre></div><div id="dffd"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(doubles)</span></span> >>> <span class="hljs-selector-attr">[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]</span></pre></div><div id="227f"><pre>from functools <span class="hljs-keyword">import</span> <span class="hljs-keyword">reduce</span> sum_all = <span class="hljs-keyword">reduce</span>(lambda x, y: x+y, lst)</pre></div><div id="f907"><pre><span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(sum_all)</span></span> >>> <span class="hljs-number">55</span></pre></div><h2 id="eb7e">4. Other Use Cases</h2><p id="bd93">For example, if we have a list of prices and volume retrieved from the order book as follows: <code>orders = [[1.21, 34600], [1.22, 56490], [1.25, 3970], [1.28, 127500], [1.3, 87900]]</code> , each element in the list represents a price-volume pair. To sort the list, we could employ lambda functions to specify the key used for sorting.</p><div id="9ad2"><pre>orders = <span class="hljs-comment">[<span class="hljs-comment">[1.21, 34600]</span>, <span class="hljs-comment">[1.22, 56490]</span>, <span class="hljs-comment">[1.25, 3970]</span>, <span class="hljs-comment">[1.28, 127500]</span>, <span class="hljs-comment">[1.3, 87900]</span>]</span></pre></div><div id="96c8"><pre># <span class="hljs-built_in">sort</span> by price sorted(orders, <span class="hljs-built_in">key</s

Options

pan>=<span class="hljs-built_in">lambda</span> x: x[<span class="hljs-number">0</span>])</pre></div><div id="cc82"><pre>>>> <span class="hljs-comment">[<span class="hljs-comment">[1.21, 34600]</span>, <span class="hljs-comment">[1.22, 56490]</span>, <span class="hljs-comment">[1.25, 3970]</span>, <span class="hljs-comment">[1.28, 127500]</span>, <span class="hljs-comment">[1.3, 87900]</span>]</span> </pre></div><div id="3cd2"><pre># <span class="hljs-built_in">sort</span> by volume sorted(orders, <span class="hljs-built_in">key</span>=<span class="hljs-built_in">lambda</span> x: x[<span class="hljs-number">1</span>])</pre></div><div id="d932"><pre>>>> <span class="hljs-comment">[<span class="hljs-comment">[1.25, 3970]</span>, <span class="hljs-comment">[1.21, 34600]</span>, <span class="hljs-comment">[1.22, 56490]</span>, <span class="hljs-comment">[1.3, 87900]</span>, <span class="hljs-comment">[1.28, 127500]</span>]</span></pre></div><h1 id="e872">Final Note</h1><p id="a64b">Internally, both <code>lambda</code> and <code>def</code> functions work exactly the same. The <code>dis</code> keyword exposes a readable version of Python bytecode allowing inspection of instructions. Evaluating both versions of <code>square</code> functions defined in the beginning of this article:</p><div id="0334"><pre><span class="hljs-comment"># both versions of functions</span> <span class="hljs-attr">square_lambda</span> = lambda x: x**<span class="hljs-number">2</span></pre></div><div id="1e98"><pre><span class="hljs-keyword">def</span> <span class="hljs-title function_">square_def</span>(<span class="hljs-params">x</span>): <span class="hljs-keyword">return</span> x**<span class="hljs-number">2</span></pre></div><div id="a1fa"><pre><span class="hljs-meta"># evaluation results</span> <span class="hljs-keyword">import</span> dis</pre></div><div id="e97d"><pre><span class="hljs-keyword">dis</span>.<span class="hljs-keyword">dis</span>(square_lambda)</pre></div><div id="080f"><pre>>>> <span class="hljs-number"> 1 </span> <span class="hljs-number"> 0 </span>LOAD_FAST <span class="hljs-number"> 0 </span>(x) <span class="hljs-number"> 2 </span>LOAD_CONST <span class="hljs-number"> 1 </span>(2) <span class="hljs-number"> 4 </span>BINARY_POWER <span class="hljs-number"> 6 </span>RETURN_VALUE</pre></div><div id="e431"><pre><span class="hljs-keyword">dis</span>.<span class="hljs-keyword">dis</span>(square_def)</pre></div><div id="f356"><pre>>>> <span class="hljs-number"> 3 </span> <span class="hljs-number"> 0 </span>LOAD_FAST <span class="hljs-number"> 0 </span>(x) <span class="hljs-number"> 2 </span>LOAD_CONST <span class="hljs-number"> 1 </span>(2) <span class="hljs-number"> 4 </span>BINARY_POWER <span class="hljs-number"> 6 </span>RETURN_VALUE</pre></div><p id="8aa3">The processes undertaken by both functions are observed to be exactly the same. So there is no real difference in the way they execute.</p><p id="17bb"><i>More content at <a href="https://plainenglish.io/"><b>PlainEnglish.io</b></a>. Sign up for our <a href="http://newsletter.plainenglish.io/"><b>free weekly newsletter</b></a>. Follow us on <a href="https://twitter.com/inPlainEngHQ"><b>Twitter</b></a><b> </b>and <a href="https://www.linkedin.com/company/inplainenglish/"><b>LinkedIn</b></a>. Check out our <a href="https://discord.gg/GtDtUAvyhW"><b>Community Discord</b></a> and join our <a href="https://inplainenglish.pallet.com/talent/welcome"><b>Talent Collective</b></a>.</i></p></article></body>

Lambda Functions in Python — Filter, Map & Reduce

Image by Author

What is Lambda Function?

Brief Intro

A lambda function is an anonymous function with syntax lambda args: expression . The expression is executed on the arguments and the result is returned. Each lambda function consists of 3 parts:

  • Keyword lambda
  • A bound variable x
  • Body of the expression

Syntax — Single Variable

A simple example: square = lambda x: x**2 is equivalent to the standard Python function definition as follows:

def square(x):
    return x**2

Use cases like square(4) will give the same results in both cases.

Syntax — Multiple Variables

Example for getting the sum of squares of 2 variables:

sum_of_square = lambda x, y: x**2 + y**2

Characteristics

As can be seen in the previous examples, a lambda function has the following characteristics:

  1. It is written as a single line of expression.
  2. It does not contain statements in the body.
  3. It does not support type annotations or additional variable declarations.

Why & When to Use Lambda Functions?

  1. In most cases, lambda functions reduce the number of lines compared to normal Python function definitions using def keyword.
  2. They are useful when a function is needed temporarily for a short period of time, often to be used inside another function such as filter , map, sort and reduce.

1. Filter

The filter function takes on the form filter(function, iterable) . It is used to filter elements satisfying certain conditions from an iterable object such as lists and sets. The function argument is often implemented using a lambda function:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
>>> [2, 4, 6, 8, 10]

2. Map

The map function takes on a similar format as filter and is used to perform a uniform operation for all elements in a sequence:

letters = ["a", "b", "c", "d", "e", "f", "g"]
letters_upper_case = list(map(lambda x: x.upper(), letters))
print(letters_upper_case)
>>> ['A', 'B', 'C', 'D', 'E', 'F', 'G']

3. Reduce

Syntax: reduce(function, sequence)

The reduce function, like map, is also used to perform an operation function on each element in the sequence. However, it works a bit differently in that the operation is performed among the elements, rather than performed on each element separately.

For example, map is used if you wish to double each element, but reduce is used if you want to get the sum of all elements in the sequence.

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
doubles = list(map(lambda x: x*2, lst))
print(doubles)
>>> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
from functools import reduce
sum_all = reduce(lambda x, y: x+y, lst)
print(sum_all)
>>> 55

4. Other Use Cases

For example, if we have a list of prices and volume retrieved from the order book as follows: orders = [[1.21, 34600], [1.22, 56490], [1.25, 3970], [1.28, 127500], [1.3, 87900]] , each element in the list represents a price-volume pair. To sort the list, we could employ lambda functions to specify the key used for sorting.

orders = [[1.21, 34600], [1.22, 56490], [1.25, 3970], [1.28, 127500], [1.3, 87900]]
# sort by price
sorted(orders, key=lambda x: x[0])
>>> [[1.21, 34600], [1.22, 56490], [1.25, 3970], [1.28, 127500], [1.3, 87900]]
# sort by volume
sorted(orders, key=lambda x: x[1])
>>> [[1.25, 3970], [1.21, 34600], [1.22, 56490], [1.3, 87900], [1.28, 127500]]

Final Note

Internally, both lambda and def functions work exactly the same. The dis keyword exposes a readable version of Python bytecode allowing inspection of instructions. Evaluating both versions of square functions defined in the beginning of this article:

# both versions of functions
square_lambda = lambda x: x**2
def square_def(x):
    return x**2
# evaluation results
import dis
dis.dis(square_lambda)
>>> 
  1           0 LOAD_FAST                0 (x)
              2 LOAD_CONST               1 (2)
              4 BINARY_POWER
              6 RETURN_VALUE
dis.dis(square_def)
>>> 
  3           0 LOAD_FAST                0 (x)
              2 LOAD_CONST               1 (2)
              4 BINARY_POWER
              6 RETURN_VALUE

The processes undertaken by both functions are observed to be exactly the same. So there is no real difference in the way they execute.

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Check out our Community Discord and join our Talent Collective.

Python
Lambda
Function
Recommended from ReadMedium