{"id":58,"date":"2024-01-24T14:34:09","date_gmt":"2024-01-24T14:34:09","guid":{"rendered":"https:\/\/learnpython.elegantwallp.com\/?p=58"},"modified":"2024-01-24T14:34:11","modified_gmt":"2024-01-24T14:34:11","slug":"python-lambda-expressions","status":"publish","type":"post","link":"https:\/\/learnpython.elegantwallp.com\/2024\/01\/24\/python-lambda-expressions\/","title":{"rendered":"Python Lambda Expressions"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you\u2019ll learn about Python lambda expressions and how to use them to write anonymous functions.<\/p>\n\n\n\n<p>Sometimes, you need to write a simple\u00a0function\u00a0that contains one expression. However, you need to use this function once. And it\u2019ll unnecessary to define that function with the\u00a0<code>def<\/code>\u00a0keyword.<\/p>\n\n\n\n<p>That\u2019s where the Python lambda expressions come into play.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What are Python lambda expressions<\/h2>\n\n\n\n<p>Python lambda expressions allow you to define anonymous functions.<\/p>\n\n\n\n<p>Anonymous functions are functions without names. The anonymous functions are useful when you need to use them once.<\/p>\n\n\n\n<p>A lambda expression typically contains one or more arguments, but it can have&nbsp;<strong>only one expression<\/strong>.<\/p>\n\n\n\n<p>The following shows the lambda expression syntax:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>lambda parameters: expression<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>It\u2019s equivalent to the following function without the\u00a0<code>\"anonymous\"<\/code>\u00a0name:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def anonymous(parameters): return expression<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Python lambda expression examples<\/h2>\n\n\n\n<p>In Python, you can pass a function to another function or return a function from another function.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1) Functions that accept a function example<\/h3>\n\n\n\n<p>The following defines a function called\u00a0<code>get_full_name()<\/code>\u00a0that format the full name from the first name and last name:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def get_full_name(first_name, last_name, formatter): return formatter(first_name, last_name)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The&nbsp;<code>get_full_name()<\/code>&nbsp;function accepts three arguments:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First name (<code>first_name<\/code>)<\/li>\n\n\n\n<li>Last name (<code>last_name<\/code>)<\/li>\n\n\n\n<li>A function that will format the full name (<code>formatter<\/code>). In turn, the&nbsp;<code>formatter<\/code>&nbsp;function accepts two arguments first name and last name.<\/li>\n<\/ul>\n\n\n\n<p>The following defines two functions that return a full name from the first name and last name in different formats:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def first_last(first_name, last_name): return f\"{first_name} {last_name}\" def last_first(first_name, last_name): return f\"{last_name}, {first_name}\"<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>And this shows you how to call the\u00a0<code>get_full_name()<\/code>\u00a0function by passing the first name, last name, and\u00a0<code>first_last<\/code>\u00a0\/\u00a0<code>last_first<\/code>\u00a0functions:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>full_name = get_full_name('John', 'Doe', first_last) print(full_name) <em># John Doe<\/em> full_name = get_full_name('John', 'Doe', last_first) print(full_name) <em># Doe, John<\/em><\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>John Doe Doe, John<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Instead of defining the&nbsp;<code>first_last<\/code>&nbsp;and&nbsp;<code>last_first<\/code>&nbsp;functions, you can use lambda expressions.<\/p>\n\n\n\n<p>For example, you can express the\u00a0<code>first_last<\/code>\u00a0function using the following lambda expression:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>lambda first_name,last_name: f\"{first_name} {last_name}\"<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>This lambda expression accepts two arguments and concatenates them into a formatted string in the order&nbsp;<code>first_name<\/code>, space, and&nbsp;<code>last_name<\/code>.<\/p>\n\n\n\n<p>And the following converts the\u00a0<code>last_first<\/code>\u00a0function using a lambda expression that returns the full name in the format: last name, space, and first name:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>lambda first_name, last_name: f\"{last_name} {first_name}\";<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>By using lambda expressions, you can call the\u00a0<code>get_full_name()<\/code>\u00a0function as follows:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def get_full_name(first_name, last_name, formatter): return formatter(first_name, last_name) full_name = get_full_name( 'John', 'Doe', lambda first_name, last_name: f\"{first_name} {last_name}\" ) print(full_name) full_name = get_full_name( 'John', 'Doe', lambda first_name, last_name: f\"{last_name} {first_name}\" ) print(full_name) <\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>John Doe Doe, John<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">2) Functions that return a function example<\/h3>\n\n\n\n<p>The following\u00a0<code>times()<\/code>\u00a0function returns a function which is a lambda expression:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def times(n): return lambda x: x * n<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>And this example shows how to call the&nbsp;<code>times()<\/code>&nbsp;function:<code>double = times(2)<\/code><small>Code language: Python (python)<\/small><\/p>\n\n\n\n<p>Since the\u00a0<code>times()<\/code>\u00a0function returns a function, the\u00a0<code>double<\/code>\u00a0is also a function. To call it, you place parentheses like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>result = double(2) print(result) result = double(3) print(result)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>4 6<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The following shows another example of using the\u00a0<code>times()<\/code>\u00a0function:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>triple = times(3) print(triple(2)) <em># 6<\/em> print(triple(3)) <em># 9<\/em><\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Python lambda in a loop<\/h2>\n\n\n\n<p>See the following example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>callables = &#91;] for i in (1, 2, 3): callables.append(lambda: i) for f in callables: print(f()) <\/code><small>Code language: PHP (php)<\/small><\/code><\/pre>\n\n\n\n<p>How it works.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First, define a list with the name callables.<\/li>\n\n\n\n<li>Second, iterate from 1 to 3, create a new lambda expression in each iteration, and add it to the callables list.<\/li>\n\n\n\n<li>Third, loop over the callables and call each function.<\/li>\n<\/ul>\n\n\n\n<p>The expected output will be:<code>1 2 3<\/code><\/p>\n\n\n\n<p>However, the program shows the following output:<code>3 3 3<\/code><\/p>\n\n\n\n<p>The problem is that all the there lambda expressions reference the&nbsp;<code>i<\/code>&nbsp;variable, not the current value of&nbsp;<code>i<\/code>. When you call the lambda expressions, the value of the variable&nbsp;<code>i<\/code>&nbsp;is 3.<\/p>\n\n\n\n<p>To fix this, you need to bind the\u00a0<code>i<\/code>\u00a0variable to each lambda expression at the time the lambda expression is created. One way to do it is to use the\u00a0default argument:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>callables = &#91;] for i in (1, 2, 3): callables.append(lambda a=i: a) for f in callables: print(f()) <\/code><small>Code language: PHP (php)<\/small><\/code><\/pre>\n\n\n\n<p>In this example, the value of a is evaluated at the time the lambda expression is created. Therefore, the program returns the expected output.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you\u2019ll learn about Python lambda expressions and how to use them to write anonymous functions. Sometimes, you need to write a simple\u00a0function\u00a0that contains one expression. However, you need to use this function once. And it\u2019ll unnecessary to define that function with the\u00a0def\u00a0keyword. That\u2019s where the Python lambda expressions come into play. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[18],"tags":[],"class_list":["post-58","post","type-post","status-publish","format-standard","hentry","category-4-functions"],"_links":{"self":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/58","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/comments?post=58"}],"version-history":[{"count":1,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/58\/revisions"}],"predecessor-version":[{"id":59,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/58\/revisions\/59"}],"wp:attachment":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/media?parent=58"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/categories?post=58"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/tags?post=58"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}