{"id":7348,"date":"2019-06-23T22:04:52","date_gmt":"2019-06-23T16:34:52","guid":{"rendered":"https:\/\/techbeamers.com\/?p=7348"},"modified":"2025-11-30T10:50:57","modified_gmt":"2025-11-30T15:50:57","slug":"lambda-function-usage-python","status":"publish","type":"post","link":"https:\/\/techbeamers.com\/lambda-function-usage-python\/","title":{"rendered":"Python Lambda Usage"},"content":{"rendered":"\n<p>Brace yourself, in this tutorial, we&#8217;ll uncover the ins and outs of lambda function usage in Python with this in-depth tutorial.<\/p>\n\n\n\n<p>You&#8217;ll be able to learn when to harness their power and when to avoid them. However, you can read our comprehensive tutorial on <a href=\"https:\/\/techbeamers.com\/python-lambda\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python lambda<\/a> covering this topic in detail. Don&#8217;t miss to read it if you are first time using the lambda function.<\/p>\n\n\n\n<p>Let&#8217;s explore the world of compact functions and discover their limitless possibilities!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-understanding-the-lambda-function-usage\">Understanding the Lambda Function Usage<\/h2>\n\n\n\n<p>Let&#8217;s first quickly understand what is lambda in Python.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-what-is-lambda-in-python\">What is lambda in Python?<\/h3>\n\n\n\n<p>Python provides the ability to create concise <a href=\"https:\/\/techbeamers.com\/python-function\/\" target=\"_blank\" rel=\"noopener\">anonymous functions<\/a>, referred to as lambda functions, using the &#8220;lambda&#8221; keyword. These functions lack a name and are defined in a single line. Our comprehensive explanation of Python lambda functions will allow for a thorough understanding of their functionality.<\/p>\n\n\n\n<p>Lambda functions are structured similarly to traditional functions, executing a block of code and returning a value. As an illustration, consider the following example defining a lambda function that multiplies two numbers.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&gt;&gt;&gt; mul = lambda a, b: a * b\n&gt;&gt;&gt; mul(2, 8)\n16<\/pre>\n\n\n\n<p>Moreover, the same function, we can create using the def keyword. See the code below:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&gt;&gt;&gt; def mul(a, b):\n...     return a * b\n&gt;&gt;&gt; mul(2, 8)\n16<\/pre>\n\n\n\n<p>Also Read: <a href=\"https:\/\/techbeamers.com\/higher-order-functions-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">Higher Order Functions in Python<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-what-advantage-does-lambda-offer-why-do-you-need-it\">What advantage does lambda offer? Why do you need it?<\/h3>\n\n\n\n<p>Firstly, you should note that you don&#8217;t have to use lambda at all. There is nothing that forces you to do it. You can code any logic without using it. However, it brings ease while coding in specific scenarios. For example &#8211; When you need a function that is short and straightforward. Also, you need to call it once in a program&#8217;s life.<\/p>\n\n\n\n<p>Usually, a programmer writes functions with two objectives in mind:<\/p>\n\n\n\n<ul class=\"rb-list wp-block-list\">\n<li>To eliminate redundant code<\/li>\n\n\n\n<li>To improve modularity<\/li>\n<\/ul>\n\n\n\n<p>Assume, you have a project which has a lot of unnecessary code in several of its modules. You can create a single definition, assign some proper name, include it, and use it in all places.<\/p>\n\n\n\n<p>On the other hand, there is one piece of code that does a pre-defined task. But it is a short and complicated code that hampers the overall readability. Hence, it is deemed reasonable to wrap this block in a function.<\/p>\n\n\n\n<p>Here, the question comes that the function would get called once, so why give it a name? It should be &#8220;anonymous&#8221; instead. And we can have it defined inline where it is required. That\u2019s the situation where lambda is useful.<\/p>\n\n\n\n<p>Lambda can provide a quick shortcut to a function. Check the below Python example for writing lambdas to sort a list using some key.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&gt;&gt;&gt; sorted(range(-3, 9), key=lambda x: x ** 3)\n[-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8]<\/pre>\n\n\n\n<p>A lambda function also supports lexical closures, which means that it can retain values from its lexical neighbors while going out of scope. See the Python code below.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def makeAdder(new):\n    return lambda summation: summation + new\n\nadd_3 = makeAdder(3)\nadd_4 = makeAdder(4)\nprint(add_3(6))\nprint(add_4(6))<\/pre>\n\n\n\n<p>After the execution, the output is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">9\n10<\/pre>\n\n\n\n<p>In the above sample code, the (summation + new) lambda retains the value of &#8220;new&#8221; from the makeAdder() function.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-lambda-function-usage\">Lambda function usage<\/h3>\n\n\n\n<p>There are many situations where a lambda function is the shortest way to implement the logic.<\/p>\n\n\n\n<p>When you want to return a function from some other function, it is better to use lambda. Check out the lambda usage in Python code shown below.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&gt;&gt;&gt; def summation(new):\n...     return lambda x: x + new\n...\n&gt;&gt;&gt; proc = summation(7)\n&gt;&gt;&gt; proc(3)\n10<\/pre>\n\n\n\n<p>The above approach works as the basis of making function wrappers, for example &#8211; Python decorator.<\/p>\n\n\n\n<p>Lambda is useful for concatenating the elements of a list using reduce() method. Check how the below Python code is using it.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&gt;&gt;&gt; from functools import reduce\n&gt;&gt;&gt; reduce(lambda x, y: '{}, {}'.format(x, y), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n'0, 1, 2, 3, 4, 5, 6, 7, 8, 9'<\/pre>\n\n\n\n<p>Another usage (sorting by alternate key) which we explained above.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&gt;&gt;&gt; sorted([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda m: abs(7-m))\n[7, 6, 8, 5, 9, 4, 3, 2, 1, 0]<\/pre>\n\n\n\n<p>You can use the lambda function in your routine programming tasks. However, it may make you take some time to get used to, but after understanding, you should be able to use it with ease.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-when-to-not-use-a-lambda-function\">When to not use a lambda function?<\/h3>\n\n\n\n<ul class=\"rb-list wp-block-list\">\n<li>You won&#8217;t use something that doesn\u2019t return a value with lambda. If it isn\u2019t an expression, then you shouldn&#8217;t place it inside a lambda.<\/li>\n\n\n\n<li>Don&#8217;t put assignment statements into lambda as they don&#8217;t return anything.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-when-should-you-be-using-it\">When should you be using it?<\/h3>\n\n\n\n<ul class=\"rb-list wp-block-list\">\n<li>Expressions using maths operators, strings, and list comprehensions are all good candidates to use with lambda.<\/li>\n\n\n\n<li>Making a function call is okay. For example &#8211; print() is a function in Python, hence, is allowed in lambda.<\/li>\n\n\n\n<li>Lambda also accepts functions that return None along with conditional expressions.<\/li>\n<\/ul>\n\n\n\n<p>And certainly, you won&#8217;t want to miss the below tutorials:<\/p>\n\n\n\n<ul class=\"rb-list wp-block-list\">\n<li><a class=\"LinkSuggestion__Link-sc-1gewdgc-4 cLBplk\" href=\"https:\/\/techbeamers.com\/find-palindromes-anagrams-list-strings-python\/\" target=\"_blank\" rel=\"noopener\">Use Python Lambda to Find Palindromes and Anagrams<\/a><\/li>\n\n\n\n<li><a class=\"LinkSuggestion__Link-sc-1gewdgc-4 cLBplk\" href=\"https:\/\/techbeamers.com\/python-filter-function\/\" target=\"_blank\" rel=\"noopener\">Python Filter()<\/a><\/li>\n\n\n\n<li><a class=\"LinkSuggestion__Link-sc-1gewdgc-4 cLBplk\" href=\"https:\/\/techbeamers.com\/python-map-function\/\" target=\"_blank\" rel=\"noopener\">Python Map()<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Brace yourself, in this tutorial, we&#8217;ll uncover the ins and outs of lambda function usage in Python with this in-depth tutorial. You&#8217;ll be able to learn when to harness their power and when to avoid them. However, you can read our comprehensive tutorial on Python lambda covering this topic in detail. Don&#8217;t miss to read [&hellip;]<\/p>\n","protected":false},"author":321,"featured_media":7349,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","jetpack_post_was_ever_published":false},"categories":[92],"tags":[],"class_list":{"0":"post-7348","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-python-programming-tutorials"},"jetpack_featured_media_url":"https:\/\/techbeamers.com\/wp-content\/uploads\/2019\/06\/Python-lambda-usage-with-examples.png","_links":{"self":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/7348","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/users\/321"}],"replies":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/comments?post=7348"}],"version-history":[{"count":1,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/7348\/revisions"}],"predecessor-version":[{"id":23489,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/7348\/revisions\/23489"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/media\/7349"}],"wp:attachment":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/media?parent=7348"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/categories?post=7348"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/tags?post=7348"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}