{"id":808,"date":"2018-08-18T23:25:29","date_gmt":"2018-08-18T23:25:29","guid":{"rendered":"http:\/\/www.afternerd.com\/blog\/?p=808"},"modified":"2019-04-06T20:43:12","modified_gmt":"2019-04-06T20:43:12","slug":"python-lambdas","status":"publish","type":"post","link":"https:\/\/www.afternerd.com\/blog\/python-lambdas\/","title":{"rendered":"Python Lambdas Explained (With Examples)"},"content":{"rendered":"<p>In this article, I will teach you exactly what a python lambda is.<\/p>\n<p>As a matter of fact if you know what functions are and how to define functions in Python then you already know what a lambda is.<\/p>\n<p>A Python lambda is just a Python function.<\/p>\n<p>But may be like a special type of function that have limited capabilities \ud83d\ude42<\/p>\n<p>If you want to dive deeper and learn more about lambdas and how they are used in Python then this is what this article is about.<\/p>\n<p>Here is what I will be talking about in this article.<\/p>\n<ul>\n<li><a href=\"#what-is-python-lambda\">What is Python lambda?<\/a><\/li>\n<li><a href=\"#lambdas-with-multiple-arguments\">Lambdas with multiple arguments<\/a><\/li>\n<li><a href=\"#lambdas-with-no-arguments\">Lambdas with no arguments<\/a><\/li>\n<li><a href=\"#multiline-lambdas\">Multiline lambdas<\/a><\/li>\n<li><a href=\"#examples-of-lambda-in-action\">Examples of lambda in action<\/a>\n<ul>\n<li><a href=\"#using-lambdas-map\">Using lambdas with map<\/a><\/li>\n<li><a href=\"#using-lambdas-filter\">Using lambdas with filter<\/a><\/li>\n<li><a href=\"#using-lambdas-list-sorting\">Using lambdas with list sorting<\/a><\/li>\n<\/ul>\n<\/li>\n<li><a href=\"#expressions-vs-statements\">Expressions vs Statements<\/a><\/li>\n<\/ul>\n<h2 id=\"what-is-python-lambda\">What is Python lambda?<\/h2>\n<p>Before trying to understand what a Python lambda is, let&#8217;s first try to understand what a Python function is at a much deeper level.<\/p>\n<p>This will require a little bit of a paradigm shift of how you think about functions.<\/p>\n<p>As you already know, everything in Python is an <strong>object<\/strong>.<\/p>\n<p>For example, when we run this simple line of code.<\/p>\n<pre class=\"prettyprint\"><code>x = 5<\/code><\/pre>\n<p>What actually happens is we&#8217;re creating a Python object of type <span class=\"symbol\">int<\/span> that stores the value 5.<\/p>\n<p><span class=\"symbol\">x<\/span> is essentially a symbol that is referring to that object.<\/p>\n<p>Now let&#8217;s check the type of x and the address it is referring to.<\/p>\n<p>We can easily do that using the <span class=\"symbol\">type<\/span> and the <span class=\"symbol\">id<\/span> built-in functions.<\/p>\n<pre class=\"prettyprint\"><code>&gt;&gt;&gt; type(x)\r\n&lt;class 'int'&gt;\r\n&gt;&gt;&gt; id(x)\r\n4308964832<\/code><\/pre>\n<p>As you can see, <span class=\"symbol\">x<\/span> refers to an object of type <strong>int<\/strong> and this object lives in the address returned by the <span class=\"symbol\">id<\/span><\/p>\n<p>Pretty straightforward stuff.<\/p>\n<p>Now what happens when we define a function like this one:<\/p>\n<pre class=\"prettyprint\"><code>&gt;&gt;&gt; def f(x):\r\n...   return x * x\r\n...<\/code><\/pre>\n<p>Let&#8217;s repeat the same exercise from above and inspect the <strong>type<\/strong> of <strong>f<\/strong> and its <strong>id<\/strong>.<\/p>\n<pre class=\"prettyprint\"><code>&gt;&gt;&gt; def f(x):\r\n...   return x * x\r\n...\r\n&gt;&gt;&gt; type(f)\r\n&lt;class 'function'&gt;\r\n&gt;&gt;&gt; id(f)\r\n4316798080<\/code><\/pre>\n<p>hmm, very interesting.<\/p>\n<p>So it turns out there is a <strong>function<\/strong> class in Python and the function <span class=\"symbol\">f<\/span> that we just defined is an instance of that class.<\/p>\n<p>Exactly like how <span class=\"symbol\">x<\/span> was an instance of the <strong>integer<\/strong> class.<\/p>\n<p>In other words, you can literally think about functions the same way you think about variables.<\/p>\n<p>The only difference is that a variable stores data whereas a function stores code.<\/p>\n<p>That also means you can pass functions as arguments to other functions, or even have a function be the return value of another function.<\/p>\n<p>let&#8217;s look at a simple example where you can pass the above function <span class=\"symbol\">f<\/span> to another function.<\/p>\n<pre class=\"prettyprint\"><code>def f(x):\r\n    return x * x\r\n\r\ndef modify_list(L, fn):\r\n    for idx, v in enumerate(L):\r\n        L[idx] = fn(v)\r\n\r\nL = [1, 3, 2]\r\nmodify_list(L, f)\r\nprint(L)\r\n\r\n#output: [1, 9, 4]<\/code><\/pre>\n<p>Give yourself a minute and try to understand what this code does before you read on&#8230;<\/p>\n<p>As you can see, <strong>modify_list<\/strong> is a function that takes a list <span class=\"symbol\">L<\/span> and a function <span class=\"symbol\">fn<\/span> as arguments.<\/p>\n<p>It then iterates over the list item-by-item and applies the function <strong>fn<\/strong> on each.<\/p>\n<p>This is a very generic way of modifying the items of a list as it allows you to pass in the function that is responsible for the modification which can be very useful as you will see later.<\/p>\n<p>So for example when we pass the function <span class=\"symbol\">f<\/span> to <strong>modify_list<\/strong>, the result will be that each item in the list will be squared.<\/p>\n<p>We could pass any other custom function that can modify the list in any arbitrary way.<\/p>\n<p>That&#8217;s pretty powerful stuff right there!<\/p>\n<p>Alright now that I have laid down some foundations, let&#8217;s talk about lambdas.<\/p>\n<p>A <em>Python lambda<\/em> is just another method to define a <em>function<\/em>.<\/p>\n<p>The general syntax of a Python lambda is:<\/p>\n<blockquote><p>lambda arguments: expression<\/p><\/blockquote>\n<p>Lambda functions can accept <strong>zero<\/strong> or <strong>more<\/strong> arguments but\u00a0<strong>only one<\/strong> expression.<\/p>\n<p>The return value of the lambda function is the value that this expression is evaluated to.<\/p>\n<p>For example, if we want to define the same function <strong>f<\/strong> that we defined before using lambda syntax, this is how it will look like:<\/p>\n<pre class=\"prettyprint\"><code>&gt;&gt;&gt; f = lambda x: x * x\r\n&gt;&gt;&gt; type(f)\r\n&lt;class 'function'&gt;<\/code><\/pre>\n<p>But you might be asking yourself why the need for lambdas in the first place when we can just define functions the <em>traditional way?<\/em><\/p>\n<p>Fair question!<\/p>\n<p>Actually, lambdas are only useful when you want to define a one-off function.<\/p>\n<p>In other words, a function that will be used only once in your program. These functions are called <em>anonymous functions.<\/em><\/p>\n<p>As you will see later, there are many situations where anonymous functions can be useful.<\/p>\n<h2 id=\"lambdas-with-multiple-arguments\">Lambdas with multiple arguments<\/h2>\n<p>As you saw earlier, it was easy to define a lambda function with one argument.<\/p>\n<pre class=\"prettyprint\"><code>&gt;&gt;&gt; f = lambda x: x * x\r\n&gt;&gt;&gt; f(5)\r\n25<\/code><\/pre>\n<p>But if you want to define a lambda function that accepts more than one argument, you can separate the input arguments by commas.<\/p>\n<p>For example, say we want to define a lambda that takes two integer arguments and returns their product.<\/p>\n<pre class=\"prettyprint\"><code>&gt;&gt;&gt; f = lambda x, y: x * y\r\n&gt;&gt;&gt; f(5, 2)\r\n10<\/code><\/pre>\n<p>Nice!<\/p>\n<p>How about if you want to have a lambda that accepts no arguments whatsoever?<\/p>\n<h2 id=\"lambdas-with-no-arguments\">Lambdas with no arguments<\/h2>\n<p>Say you want to define a lambda function that takes no arguments and returns <strong>True<\/strong>.<\/p>\n<p>You can achieve this with the following code.<\/p>\n<pre class=\"prettyprint\"><code>&gt;&gt;&gt; f = lambda: True\r\n&gt;&gt;&gt; f()\r\nTrue<\/code><\/pre>\n<h2 id=\"multiline-lambdas\">Multiline lambdas<\/h2>\n<p>Yes, at some point in your life you will be wondering if you can have a lambda function with multiple lines.<\/p>\n<p>And the answer is:<\/p>\n<p>No you can&#8217;t \ud83d\ude42<\/p>\n<p>Python lambda functions accept only one and only one expression.<\/p>\n<p>If your function has multiple expressions\/statements, you are better off defining a function the traditional way instead of using lambdas.<\/p>\n<h2 id=\"examples-of-lambda-in-action\">Examples of Lambda in action<\/h2>\n<p>Now let&#8217;s discuss some of the most common places where python lambdas are heavily used.<\/p>\n<h3 id=\"using-lambdas-map\">Using lambdas with map<\/h3>\n<p>One common operation you will apply to Python lists is to apply an operation to each item.<\/p>\n<p><strong>Map<\/strong> is a Python built-in function that takes in a <strong>function<\/strong> and a <strong>sequence<\/strong> as arguments and then calls the input function on each item of the sequence.<\/p>\n<p>For example, assume we have a list of integers and we want to square each element of the list using the <strong>map<\/strong> function.<\/p>\n<pre class=\"prettyprint\"><code>&gt;&gt;&gt; L = [1, 2, 3, 4]\r\n&gt;&gt;&gt; list(map(lambda x: x**2, L))\r\n[1, 4, 9, 16]<\/code><\/pre>\n<p>Note that in Python3, the map function returns a <strong>Map<\/strong> object whereas in Python2 it returns a <strong>list<\/strong>.<\/p>\n<p>See, instead of defining a function and then passing it to map as an argument, you can just use lambdas to quickly define a function inside the map parentheses.<\/p>\n<p>This makes sense especially if you are not going to use this function again in your code.<\/p>\n<p>Let&#8217;s take a look at another case where lambdas can be useful.<\/p>\n<h3 id=\"using-lambdas-filter\">Using lambdas with filter<\/h3>\n<p>As the name suggests, <strong>filter<\/strong> is another built-in function that actually filters a sequence or any iterable object.<\/p>\n<p>In other words, given any iterable object (like a list), the <strong>filter<\/strong> function <em>filters out<\/em> some of the elements while keeping some based on some criteria.<\/p>\n<p>This criteria is defined by the caller of <strong>filter<\/strong> by passing in a function as an argument.<\/p>\n<p>This function is applied to each element of the iterable.<\/p>\n<p>If the return value is <strong>True<\/strong>, the element is kept. Otherwise, the element is disregarded.<\/p>\n<p>for example, let&#8217;s define a very simple function that returns <strong>True<\/strong> for even numbers and <strong>False<\/strong> for odd numbers:<\/p>\n<pre class=\"prettyprint\"><code>def even_fn(x):\r\n  if x % 2 == 0:\r\n    return True\r\n  return False\r\n\r\nprint(list(filter(even_fn, [1, 3, 2, 5, 20, 21])))\r\n\r\n#output: [2, 20]<\/code><\/pre>\n<p>That said, With the magic of lambdas you can do the same thing more succinctly.<\/p>\n<p>The above code will transform into this one-liner<\/p>\n<pre class=\"prettyprint\"><code>print(list(filter(lambda x: x % 2 == 0, [1, 3, 2, 5, 20, 21])))<\/code><\/pre>\n<p>And that, my friend, is the <em>power of lambdas<\/em>.<\/p>\n<h3 id=\"using-lambdas-list-sorting\">Using lambdas with list sorting<\/h3>\n<p><a href=\"https:\/\/www.afternerd.com\/blog\/python-sort-list\/\" target=\"_blank\" rel=\"noopener\">Sorting a Python list<\/a> is a very common operation.<\/p>\n<p>In fact I have a whole <a href=\"https:\/\/www.afternerd.com\/blog\/python-sort-list\/\" target=\"_blank\" rel=\"noopener\">in-depth article<\/a> dedicated to this topic.<\/p>\n<p>If you have a list of numbers or strings, then sorting a list is very straightforward.<\/p>\n<p>You can just use the <span class=\"symbol\">sort<\/span> or <span class=\"symbol\">sorted<\/span> built-in functions.<\/p>\n<p>However, sometimes you have a list of custom objects and may be you want to sort the list based on a specific object field.<\/p>\n<p>In this case, you can pass an optional <strong>key<\/strong> parameter to either <strong>sort<\/strong> or <strong>sorted<\/strong>.<\/p>\n<p>This <strong>key<\/strong> parameter is actually of type <strong>function.<\/strong><\/p>\n<p>The function is applied to all the list items and the return value is what&#8217;s going to be sorted.<\/p>\n<p>Let&#8217;s take an example.<\/p>\n<p>Assume you have an <span class=\"symbol\">Employee<\/span> class that looks like this<\/p>\n<pre class=\"prettyprint\"><code>class Employee:\r\n    def __init__(self, name, age):\r\n        self.name = name\r\n        self.age = age<\/code><\/pre>\n<p>Now Let&#8217;s create some <span class=\"symbol\">Employee<\/span> objects and append them to a list.<\/p>\n<pre class=\"prettyprint\"><code>Alex = Employee('Alex', 20)\r\nAmanda = Employee('Amanda', 30)\r\nDavid = Employee('David', 15)\r\nL = [Alex, Amanda, David]<\/code><\/pre>\n<p>Now say we want to sort this list based on the <span class=\"symbol\">age<\/span> of the employees, here is what we should do:<\/p>\n<pre class=\"prettyprint\"><code>L.sort(key=lambda x: x.age)\r\nprint([item.name for item in L])\r\n# output: ['David', 'Alex', 'Amanda']<\/code><\/pre>\n<p>See how we used a lambda expression as the <strong>key<\/strong> parameter instead of having to define a function externally and then passing this function to <strong>sort<\/strong>.<\/p>\n<h2 id=\"expressions-vs-statements\">One word on Expressions vs Statements<\/h2>\n<p>Like I mentioned earlier, lambdas can use only <em>one expression<\/em> as the body of the lambda function.<\/p>\n<p>Notice I didn&#8217;t say <em>one statement<\/em>.<\/p>\n<p>Statements and expressions are two different things but they can be confusing so let me try to clarify the differences.<\/p>\n<p>In programming languages, a statement is a line of code that does something but it doesn&#8217;t evaluate to a value.<\/p>\n<p>For example, an <strong>if statement<\/strong>, a <strong>for loop<\/strong>, a <strong>while loop<\/strong>, all of these are examples of statements.<\/p>\n<p>You can&#8217;t simply replace the statement with a value because statements don&#8217;t evaluate to a value.<\/p>\n<p>Expressions on the other hand are evaluated to a value.<\/p>\n<p>You can easily replace all the expressions in your programs with some values and your program will work correctly.<\/p>\n<p>For example:<\/p>\n<p><span class=\"symbol\">3 + 5<\/span> is an expression that is evaluation to <strong>8<\/strong><\/p>\n<p><span class=\"symbol\">10 &gt; 5<\/span> is an expression that is evaluated to <strong>True<\/strong><\/p>\n<p><span class=\"symbol\">True and (5 &lt; 3)<\/span> is an expression that is evaluated to <strong>False<\/strong><\/p>\n<p>Lambda&#8217;s body has to be an expression because the value of this expression is the return value of the function.<\/p>\n<p>Make sure you remember this point when you are writing your next lambda function \ud83d\ude42<\/p>\n<h3>Learning Python?<\/h3>\n<p>Check out <a href=\"https:\/\/courses.afternerd.com\/\">the Courses section!<\/a><\/p>\n\n<h2>Featured Posts<\/h2>\n<ul>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/learn-python\/\">The Python Learning Path (From Beginner to Mastery)<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/learn-computer-science\/\">Learn Computer Science (From Zero to Hero)<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/coding-interview\/\">Coding Interview Preparation Guide<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/stock-investing-for-beginners\/\">The Programmer&#8217;s Guide to Stock Market Investing<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/start-programming-blog\/\">How to Start Your Programming Blog?<\/a><\/li>\n<\/ul>\n<div class=\"after-post-box\">\n<h2>Are you Beginning your Programming Career?<\/h2>\n<h3>I provide my best content for beginners in the newsletter.<\/h3>\n<ul>\n<li>Python tips for beginners, intermediate, and advanced levels.<\/li>\n<li>CS Career tips and advice.<\/li>\n<li>Special discounts on my premium courses when they launch.<\/li>\n<\/ul>\n<p>And so much more&#8230;<\/p>\n<h3>Subscribe now. It&#8217;s Free.<\/h3>\n<p><script type=\"text\/javascript\" src=\"\/\/mautic.afternerd.com\/form\/generate.js?id=2\"><\/script><\/p>\n<\/div>\n\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":915,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[12],"tags":[13],"yst_prominent_words":[795,784,807,800,806,160,794,655,790,656,805,798,799,225,791,158,658,776,657,804],"_links":{"self":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts\/808"}],"collection":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/comments?post=808"}],"version-history":[{"count":25,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts\/808\/revisions"}],"predecessor-version":[{"id":1477,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts\/808\/revisions\/1477"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/media\/915"}],"wp:attachment":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/media?parent=808"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/categories?post=808"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/tags?post=808"},{"taxonomy":"yst_prominent_words","embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/yst_prominent_words?post=808"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}