<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged lambda-functions</title>
<link>https://coderlegion.com/tag/lambda-functions</link>
<description>Powered by Question2Answer</description>
<item>
<title>DevLog 20250510 Dealing with Lambda</title>
<link>https://coderlegion.com/3065/devlog-20250510-dealing-with-lambda</link>
<description>&lt;p&gt;(The technical term is &quot;Closure&quot;)&lt;/p&gt;
&lt;p&gt;The essence of lambda calculus is with captures - be it simple values or object references. At the site of anonymous function declaration, it's being captured and (the reference) is saved inside the lambda until being invoked.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// C# – Capturing a local variable in a LINQ query
int factor = 3;
int[] numbers = { 1, 2, 3, 4, 5 };
var scaled = numbers
    .Select(n =&amp;gt; n * factor)   // ‘factor’ is captured from the enclosing scope
    .ToArray();
Console.WriteLine(string.Join(&quot;, &quot;, scaled));  // 3, 6, 9, 12, 15
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In C++ this is more explicit, and the capturing process is more obvious:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// C++20 – Capturing a local variable in a ranges pipeline
#include &amp;lt;iostream&amp;gt;
#include &amp;lt;vector&amp;gt;
#include &amp;lt;ranges&amp;gt;

int main() {
    int factor = 3;
    std::vector&amp;lt;int&amp;gt; numbers = { 1, 2, 3, 4, 5 };

    // Capture ‘factor’ by value in the lambda
    auto scaled = numbers 
        | std::views::transform([factor](int n) { return n * factor; });

    for (int x : scaled)
        std::cout &amp;lt;&amp;lt; x &amp;lt;&amp;lt; &quot; &quot;;   // 3 6 9 12 15
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What happens when an object reference is disposed, as in the case of &lt;code&gt;IDisposable&lt;/code&gt;? It will simply throw an error.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Create and use a MemoryStream
        var ms = new MemoryStream();
        ms.WriteByte(0x42);                // OK: writes a byte

        // Dispose the stream
        ms.Dispose();                      // Unmanaged buffer released

        try
        {
            // Any further operation is invalid
            ms.WriteByte(0x24);            // &amp;lt;-- throws ObjectDisposedException
        }
        catch (ObjectDisposedException ex)
        {
            Console.WriteLine($&quot;Cannot use disposed object: {ex.GetType().Name}&quot;);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c87yyhj6tqyth0sf3ddi.png&quot; alt=&quot;IDisposable capture runtime exception&quot;&gt;&lt;/p&gt;
&lt;p&gt;An important distinction is events or plain callbacks that requires no return value, which can be implemented quite plainly.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/irt8ep76g8kibc5tb1hd.png&quot; alt=&quot;Divooka procedural context custom event&quot;&gt;&lt;/p&gt;
&lt;p&gt;To achieve the same in a dataflow context, some kind of GUI (or &quot;graph-native&quot;) support is needed, and to the caller, it's clear (in the language of C#) it's taking a delegate as argument, as in the case of LINQ &lt;code&gt;Select&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0j8mzw6jfcxnlplhgx4i.png&quot; alt=&quot;Example of &amp;quot;Apply&amp;quot; with delegate input&quot;&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public static System.Collections.Generic.IEnumerable&amp;lt;TResult&amp;gt; Select&amp;lt;TSource,TResult&amp;gt;(this System.Collections.Generic.IEnumerable&amp;lt;TSource&amp;gt; source, Func&amp;lt;TSource,int,TResult&amp;gt; selector);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To implement capturing, the most natural way is to ensure it happens &quot;in-place&quot; - directly on the graph. With this approach, we don’t need specialized nodes for every kind of function; we can instead rely on existing language constructs to handle the rest.&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4minad52ehm5to3j26kk.png&quot; alt=&quot;Final implementation&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5mfu3m8xwtqj42icd6yc.png&quot; alt=&quot;Demo Function&quot;&gt;&lt;/p&gt;
&lt;p&gt;The last bit is actually inspired by Haskell, where functions are first-class and can be composed:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;-- A simple two‑argument function
add :: Int -&amp;gt; Int -&amp;gt; Int
add x y = x + y

-- Partially apply 'add' to “capture” the first argument
addFive :: Int -&amp;gt; Int
addFive = add 5

main :: IO ()
main = do
  print (addFive 10)          -- 15
  print (map (add 3) [1,2,3]) -- [4,5,6]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;See a demo of usage &lt;a rel=&quot;nofollow&quot; href=&quot;https://dev.to/methodoxdivooka/progress-share-graph-local-lambda-calculus-4dj2&quot;&gt;here&lt;/a&gt;, reposted below:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/npdq24nat7hrusu0qxrd.gif&quot; alt=&quot;Image description&quot;&gt;&lt;/p&gt;
</description>
<category>C#</category>
<guid isPermaLink="true">https://coderlegion.com/3065/devlog-20250510-dealing-with-lambda</guid>
<pubDate>Fri, 16 May 2025 19:49:54 +0000</pubDate>
</item>
<item>
<title>Mastering Lambda Functions in Python: A comprehensive Guide</title>
<link>https://coderlegion.com/272/mastering-lambda-functions-in-python-a-comprehensive-guide</link>
<description>&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; There is a function in Python named the &lt;strong&gt;lambda function&lt;/strong&gt; that is very useful for writing &lt;strong&gt;anonymous functions&lt;/strong&gt;. Now you are wondering why it is anonymous. So, it has the feature of creating a function without a name but with an expression. This is the advanced concept of Python, where you can define a function spontaneously without any doc-strings or function header. It encourages the writing of concise and to-the-point expressions, mostly when inline expression and logic are required within the expression. Therefore, in this article, we will discuss the basic understanding of the lambda function, its syntax with examples, and when and how to use this advanced feature. Let's get started!&lt;/p&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Understanding Lambda Functions&lt;/h2&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Definition of Lambda Functions&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; A &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/172/python-lambda-functions&quot; target=&quot;_blank&quot;&gt;lambda function&lt;/a&gt; is one of the simplest ways to define a &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/182/python-functions&quot; target=&quot;_blank&quot;&gt;function&lt;/a&gt; in Python. It is anonymous, defined without a name, and does not contain the &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/reference/compound_stmts.html#def&quot; title=&quot;file&quot;&gt;def&lt;/a&gt; keyword. It can accept any number of arguments but can have only one expression.&lt;/p&gt; 
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Syntax for Defining Lambda Function&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; The lambda function is always defined using the lambda keyword followed by the arguments and the expression we want to evaluate. The following is the syntax of the lambda function:&lt;/p&gt; 
&lt;pre&gt;&lt;code&gt;lambda arguments: expression
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt; Characteristics and Limitations of Lambda Function&lt;/h3&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; One of the features of many programming languages is the lambda function, known as an inline function or lambda expression. This feature allows you to write the function without any signature and expressed in a single line of code. They are like user-defined functions. Here are some of the characteristics of the lambda function:&lt;/p&gt; 
&lt;ol&gt;
 &lt;li style=&quot;text-align: justify; margin: 0.5em;&quot;&gt; Lambda functions are not created in the traditional way which means, the function has no name making them anonymous functions.&lt;/li&gt; 
 &lt;li style=&quot;text-align: justify; margin: 0.5em;&quot;&gt; Lambda functions are suitable for simple logical operations because of their simple syntax and inline nature, allowing direct use of logic without traditionally defining a complex control structure or multiple statements.&lt;/li&gt; 
 &lt;li style=&quot;text-align: justify; margin: 0.5em;&quot;&gt; It is preferred when we want only one expression in return. A lambda function reduces the need to define a separate named function when a single operation is required.&lt;/li&gt; 
 &lt;li style=&quot;text-align: justify; margin: 0.5em;&quot;&gt; A lambda function is also used as a parameter for different functions such as map and filter. They are considered first-class citizens in Python because they can be stored as variables and passed as arguments to other function signatures.&lt;/li&gt; 
 &lt;li style=&quot;text-align: justify; margin: 0.5em;&quot;&gt;They are flexible when taking any number of arguments separated by commas with different types of return values.&lt;/li&gt; 
&lt;/ol&gt; 
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt; Although the lambda function provides the concise and advanced features of defining functions in Python with its inline nature, it has some &lt;strong&gt;limitations&lt;/strong&gt; that need attention. So, let's discuss them:&lt;/p&gt; 
&lt;ol&gt;
&lt;li style=&quot;text-align: justify; margin: 0em 1em 0em 1em;&quot;&gt;Lambda functions are restricted to only one expression to ensure that they focus on a single task. For complex logic and multiple statements, they cannot deal with such cases efficiently.&lt;/li&gt; 
&lt;li style=&quot;text-align: justify; margin: 0em 1em 1em 1em;&quot;&gt;The doc-string is a feature used to explain the purpose of the function before its implementation. However, we cannot explain the inputs, operations, and outputs in lambda functions because of their inline nature.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 0.5em 1em;&quot;&gt;In addition, lambda functions are not used when the function declaration requires multiple lines of code. In addition, they are quite limited in functionality, such as loops or nested within other expressions.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2 style=&quot;margin: 0.5em;&quot;&gt;Basic Syntax and Usage&lt;/h2&gt;
&lt;h3 style=&quot;margin: 0.5em;&quot;&gt;Introduction to Basic Syntax of Lambda Functions&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1em;&quot;&gt;Mostly, &lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/reference/expressions.html#lambda&quot; title=&quot;file&quot;&gt;lambda&lt;/a&gt; functions are used when a small function is temporarily required within the program. To use the lambda function in the program, we need to understand its syntax. Its syntax is divided into four components:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=3346864496485220407&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;&lt;strong&gt;Lambda:&lt;/strong&gt; Keyword used before the implementation of the lambda function.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;&lt;strong&gt;Arguments:&lt;/strong&gt; Take as many arguments as required, where each argument or parameter is separated by a comma.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;&lt;strong&gt;Colon:&lt;/strong&gt; Acts as a separator between the arguments and the expression.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 1;&quot;&gt;&lt;strong&gt;Expression:&lt;/strong&gt; Evaluate single valid expressions, execute, and return the function result.&lt;/li&gt; 
&lt;/ul&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;Illustration of Simple Lambda Functions for Mathematical Operation&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;Now, let's discuss and illustrate the lambda function with a simple mathematical operation example of the addition of two numbers.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#addition lambda function with 2 arguments
addition = lambda x ,y: x * y 
#prints the result
print(addition(7,7))
&lt;/code&gt;&lt;/pre&gt;
&lt;div class=&quot;div-blue&quot;&gt;  
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;  
&lt;span class=&quot;alert-body&quot;&gt; For immediate execution of the lambda function, parentheses can be used around the lambda function. This makes it an immediately invoked function expression.&lt;/span&gt; 
&lt;/div&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;Another example of multiplication of 3 numbers is where we have three numbers as an argument and have one single expression.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#multiplication lambda function with 3 arguments
multiply = lambda x ,y, z: x * y * z
#prints the result
print(multiply(7,7,9))  
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;Lambda Functions with Built-in Functions like &quot;map&quot;, &quot;filter&quot;, and &quot;sorted&quot;&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;As we discussed, lambda functions are used as small functions or arguments for higher functions. These higher functions are built-in &lt;a rel=&quot;nofollow&quot; href=&quot;https://coderlegion.com/104/python-getting-started&quot; target=&quot;_blank&quot;&gt;Python&lt;/a&gt; functions such as map(), filter(), sorted(), and reduce(). We can use the lambda function as a single expression to define simple logic or operations without defining a separate function. This approach provides clarity and conciseness in the program when the function is temporarily required. Let us understand each with a code example.&lt;/p&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;&lt;strong&gt;1. filter():&lt;/strong&gt; Using the lambda function with the filter module to filter the values of the list and extract the positive numbers.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#lambda function with filter module to extract positive numbers
num = [1,57,38,-97,-56,9,2]
numbers_pos = filter(lambda x: x &amp;gt; 0, num)
#prints the result
print(list(numbers_pos))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=10323639186409347918&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;&lt;strong&gt;2. map():&lt;/strong&gt; Using the lambda function with the map module to alter all items of the list with the specified expression.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#lambda function with map module to alter the numbers
num = [1,57,38,8,56,9,2]
numbers_pos = map(lambda x: x + 7, num)
#prints the result
print(list(numbers_pos))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=18155038860099468624&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;&lt;strong&gt;3. sorted():&lt;/strong&gt; Using the lambda function with the sorting module to sort the elements in the list.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#lambda function with sort module to sorting the numbers
num = [1,57,-38,-8,56,9,2]
numbers_dessort = sorted(num, key = lambda n : -n) #-n indicate the list sorted in descending order
numbers_ascsort = sorted(num, key = lambda n : n) #n indicate the list sorted in ascending order
 #prints the result
print(&quot;In Descending Order:&quot;, list(numbers_dessort))
print(&quot;In Ascending Order:&quot;, list(numbers_ascsort))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=290626990234994486&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Lambda Functions VS Regular Functions&lt;/h2&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;Comparison Between Lambda Functions and Regular Named Functions&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;We now discuss the characteristics and limitations of the lambda function. Now, let us compare it with the regular function in different aspects. Regular and lambda functions are both used in the programming world, and each has its advantages and uses.&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;1. Syntax&lt;/h3&gt;
&lt;ol&gt;
&lt;li style=&quot;text-align: justify; margin: 0.5;&quot;&gt; A regular expression is defined using the &quot;def&quot; keyword followed by the name and parameters within parentheses and the block of code.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 0.5;&quot;&gt; Lambda functions are defined using the lambda keyword followed by the parameters, colon, and valid expression.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;#Regular Function
def square(x):
  return x*2

#Lambda Function
square = lambda x : x*2
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;2. Name&lt;/h3&gt;
&lt;ol&gt;
&lt;li style=&quot;text-align: justify; margin: 0.5;&quot;&gt; In a regular function, the name is mandatory given to the function and is used to call it everywhere in the code.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 0.5;&quot;&gt; Lambda functions as anonymous functions do not require any specified name because they are often directly called where it's defined.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;3. Parameters&lt;/h3&gt;
&lt;ol&gt;
&lt;li style=&quot;text-align: justify; margin: 0.5;&quot;&gt; Regular functions can have multiple parameters separated by commas, specified by the parentheses.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 0.5;&quot;&gt; The lambda function can also have multiple parameters specified by a colon as a separator.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;4. Function Body&lt;/h3&gt;
&lt;ol&gt;
&lt;li style=&quot;text-align: justify; margin: 0.5;&quot;&gt; Regular expression deals with the multiple pieces of code within the function definition.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 0.5;&quot;&gt; The lambda function deals with only a single valid expression that is evaluated against the parameters and returns the result.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;5. Return statement&lt;/h3&gt;
&lt;ol&gt;
&lt;li style=&quot;text-align: justify; margin: 0.5;&quot;&gt; The regular function uses the return statement to return the values from the function.&lt;/li&gt;
&lt;li style=&quot;text-align: justify; margin: 0.5;&quot;&gt; The lambda function does not require a return statement.&lt;/li&gt;&lt;/ol&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;6. Reusability&lt;/h3&gt;
&lt;ol&gt;
&lt;li style=&quot;text-align: justify; margin: 0.5;&quot;&gt;We can use regular functions multiple times by just calling the function name without explicitly using the code repeatedly.&lt;/li&gt; 
&lt;li style=&quot;text-align: justify; margin: 0.5;&quot;&gt;The lambda functions are inline and have a specific task that we cannot reuse in other parts of the code.&lt;/li&gt;&lt;/ol&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;When to Use Lambda Functions and When to Use Regular Functions?&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;Python developers mostly use the lambda function when they want to add an inline expression, which is used only once. This function cannot be called at other places in the program and is invoked only when the code is compiled. However, if we compare its use case with that of a regular function, the regular function is the traditional way of defining the function. They are mostly used for writing blocks of code that handle complex logic and are required at multiple locations.&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;Example Demonstrating the Readability and Conciseness of Lambda Functions&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;To comprehend the readability and conciseness of using the lambda function, I will demonstrate the conditional operations with the simple if-else in the lambda function expression. Here, I am mapping the list of people of age with eligibility to cast a vote.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#lambda function with map  module and conditional statement to alter the eligible one
people_age = [12,17,38,45,56,19,22]
eligibility = map(lambda age: &quot;Eligible&quot; if age &amp;gt;= 18 else &quot;Not Eligible&quot;, people_age)
#prints the result
print(list(eligibility))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=1537406762050434577&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-red&quot;&gt;  
&lt;span class=&quot;alert-header&quot;&gt;Caution:&lt;/span&gt;  
&lt;span class=&quot;alert-body&quot;&gt;Remember, we can nested multiple conditions like if-elif-else in the expression but try to avoid its incorporation as this affects the code readability.&lt;/span&gt; 
&lt;/div&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Advanced Usage of Lambda Function&lt;/h2&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;Explanation of Using Lambda Functions with Higher-Order Functions&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;The higher-order function is an advanced and popular concept in Python. It is a function that takes one or more functions as arguments. Also, said to a function that returns a function as its result. They use the lambda function as an argument to evaluate the expression. These higher-order functions are: sorted(), max(), filter(), reduce(), and so on, are built-in modules in Python. Let's define the higher-order function with a lambda function.&lt;/p&gt;
&lt;div class=&quot;div-blue&quot;&gt;  
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;  
&lt;span class=&quot;alert-body&quot;&gt;The lambda expression, an anonymous function, and lambda function are names used interchangeably.&lt;/span&gt; 
&lt;/div&gt;
&lt;pre&gt;&lt;code&gt;#lambda with higher order function
higher_funtion = lambda num, fun: num + fun(num) #takes the num and fun as two arguments
# print the num and fun expression with value
print(&quot;The Result is&quot;, higher_funtion(70, lambda num : num % 3 ))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=4365466125185953758&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;Illustration of Lambda Functions as Arguments to Functions like &quot;sorted&quot; and &quot;max&quot;&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;Lambda functions are quite popular for use as arguments with many built-in functions. Here, I illustrate the lambda function as an argument for higher-order functions one by one.&lt;/p&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;&lt;strong&gt;1. max():&lt;/strong&gt; Returns the maximum value from the iterable object i.e., list, tuples, and dictionary.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#lambda function with max module to find the maximum number
num = [1,57,-38,-8,56,9,2]
max_number = max(num, key = lambda n : n) 
 #prints the result
print(&quot;The Higher number is:&quot;,max_number)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=17924103847495017520&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;&lt;strong&gt;2. min():&lt;/strong&gt; Returns the minimum value from the iterable object i.e. list, tuples, dictionary. Here, I am using the list in the example &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#lambda function with min module to find the minimum number
num = [1,57,-38,-8,56,9,2]
min_number = min(num, key = lambda n : n) 
 #prints the result
print(&quot;The Lowest number is:&quot;,min_number)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13051385203748840717&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;&lt;strong&gt;3. reduce():&lt;/strong&gt; Returns single values after performing the computation on the iterable values.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;from functools import reduce
#lambda function with reduce module 
num = [1,7,8,4,6,9,2]
#this reduce the list based on the espression
multiple = reduce(lambda n, m : n * m, num) 
 #prints the result
print(&quot;The Result is:&quot;,multiple)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=5453503164795668233&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;&lt;strong&gt;4. zip():&lt;/strong&gt; Combines multiple lists based on the expression and returns a single list or iterable. &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;#lambda function with zip module 
num = [1,7,8,4,6,9,2]
num2 = [2,5,7,3,7,9,3]
#this zip the two list into one based on the expression
addition = map(lambda n: n[0] + n[1], zip(num, num2)) 
 #prints the result
print(&quot;The Result is:&quot;,list(addition))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=14351003267171715178&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Functional Programming Paradigm&lt;/h2&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;Introduction to Functional Programming Paradigm and its Relevance to Lambda Functions&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;Function programming is the programming technique that avoids side effects in your program by performing computation mainly through the evaluation of all functions. It relies heavily on immutable data structures. It is a programming style just like OOP that can reduce the likelihood of bugs in your code. Furthermore, it provides many features, one of which is lambda functions. However, the lambda function is used as a functional programming tool to create small functions that will be used once in a program with no need to explicitly define their name and proper function signature.&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;Explanation of Pure Functions, Side Effects, and Immutability&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;Pure functions give the same output every time the function executes with the given input without any side effects. These functions do not have any side effects like the function that followed the imperative paradigm. Instead, they preserve the definition and logic of the function. They are immutable because once the data are defined, we cannot change them, which is primarily done to avoid side effects.&lt;/p&gt;
&lt;h3 style=&quot;margin: 0.5;&quot;&gt;Demonstration of Using Lambda Functions in Functional Programming Style&lt;/h3&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;Let's demonstrate an example of a lambda function in functional programming style. Here, I create a list of strings and use the sorted() module with the lambda function to sort the list based on their length. Convert the string of the list into uppercase using the map() module.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;list_string = [&quot;hello&quot;, &quot;python&quot;, &quot;programming&quot;, &quot;world&quot;, &quot;functional&quot;] #list of string 
#sort the list based on their length
string_sort = sorted(list_string, key = lambda n: len(n) ) 
 #prints the result
print(&quot;The Result is:&quot;,string_sort)
#alter the string in uppercase
uppercase_words = list(map(lambda n: n.upper(), list_string))
print(&quot;Uppercase of list is:&quot;, uppercase_words)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=14114385190899639830&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt;Wrapping Up&lt;/h2&gt;
&lt;p style=&quot;text-align: justify; margin: 1;&quot;&gt;In conclusion, we discussed the advanced concept of Python, which includes lambda functions. This function is helpful when you want to &lt;strong&gt;write a one-liner function&lt;/strong&gt; in your program that is in one place only. They ensure an &lt;strong&gt;immediate function-invoked expression&lt;/strong&gt; approach. We also see practical examples alongside the Python code. We learned how it differs from regular functions, and each has its own use case and advantages. So, this is a good way of exploring &lt;strong&gt;functional programming&lt;/strong&gt; in Python. Thank you for reading this guide. Happy Coding!&lt;/p&gt;
&lt;hr&gt;
&lt;h2 style=&quot;margin: 0.5;&quot;&gt; Reference&lt;/h2&gt;   
&lt;p&gt;&lt;a rel=&quot;nofollow&quot; href=&quot;https://docs.python.org/3/reference/expressions.html#lambda&quot; title=&quot;file&quot;&gt;Lambda Function in Python&lt;/a&gt;  &lt;/p&gt;
</description>
<category>Adv Concepts</category>
<guid isPermaLink="true">https://coderlegion.com/272/mastering-lambda-functions-in-python-a-comprehensive-guide</guid>
<pubDate>Mon, 06 May 2024 10:02:35 +0000</pubDate>
</item>
</channel>
</rss>