Lambda Function in Python – Explained with Examples

The lambda function is a versatile tool that offers a compact and efficient way to define small anonymous functions on the fly. Imagine effortlessly crafting concise functions without the need for formal declaration. Whether you’re sorting lists, mapping values, or filtering elements, the lambda function shines with its flexibility and simplicity. 

 

Get into Python’s lambda world and experience the joy of coding with elegance and precision. Revolutionise your programming journey today with lambda functions, where creativity meets efficiency in the Pythonic realm.

 

Table of Contents:

 

 

What are Lambda Functions?

 

Lambda functions, often termed anonymous functions, resemble user-defined functions but lack a specific name.

 

They prove efficient for tasks requiring concise expressions, typically limited to single-line statements. Moreover, they serve well for one-time function usage.

 

What are Lambda Functions in Python?

 

In Python, lambda functions are anonymous, meaning they lack a specific name. While the `def` keyword is traditionally used to define functions in Python, the `lambda` keyword offers an alternative for creating unnamed functions.

 

Python Lambda Function Syntax

 

The syntax for lambda functions is: `lambda arguments: expression`.

 

Lambda functions can take any number of arguments but must contain only one expression, which gets evaluated and returned.

 

They are handy when you need a quick function without defining it using `def`.

 

Remember, lambda functions are limited to a single expression, and they find applications in various programming domains alongside other function expressions.

 

Characteristics of Lambda Functions

 

  • The lambda function allows for multiple arguments, but it’s limited to a single expression, which is then evaluated and returned. 
  • Lambda functions are commonly applied wherever function objects are needed. 
  • They’re constrained to a single expression and typically fit into a single line of code. 
  • Anonymous functions can be nested inside another function and don’t necessitate a return statement. 
  • They’re often utilised for short-term tasks, providing simplicity and usability within other functions.

 

When Should You Use a Lambda Function?

Utilise lambda functions for crafting straightforward expressions, avoiding complex structures like if-else statements and for-loops. If your task involves such complex structures, opt for a user-defined function instead of a lambda function.

Operations in Lambda Function With Examples

 

Lambda functions facilitate various operations such as:

 

  • Addition, 
  • Subtraction, 
  • Multiplication, and 
  • Division. 

 

Additionally, they enable more advanced functionalities like 

functional programming, object-oriented programming, and parameterising a method within a specific class.

 

Examples:

 

  • Addition

 

add = lambda a, b: a + b

print(add(5, 5))

# output: 10

 

Explanation: Initially, a lambda object named “add” is created. It is then initialised with two arguments, “a” and “b,” representing numbers to be added together. The addition operation is defined after the colon within the lambda expression.

 

  • Subtraction

 

subtract = lambda a, b: a – b

print(add(200, 50))

# output: 150

 

Explanation: First, a lambda object named “subtract” is declared. It is then initialised with two arguments, “a” and “b,” which are integers to be subtracted. The subtraction operation is defined after the colon within the lambda expression.

 

  • Multiplication

 

multiply = lambda a, b: a * b

print(multiply(100, 50))

# output: 5000

 

Explanation: First, a lambda object named “multiply” is declared. Then, it is initialised with two arguments, “a” and “b,” representing numbers to be multiplied. Following the colon, the multiplication expression is defined.

 

  • Division

 

div = lambda a, b: a / b

print(div(100, 50))

# output: 2

 

Explanation: Initially, a lambda object named “div” is declared. It is then initialised with two arguments, “a” and “b,” representing numbers to be used for division. The definition of the division operation follows the colon within the lambda expression.

 

Advanced Uses of Lambda Functions With Examples

 

In this segment, we delve into the utilisation of lambda functions in conjunction with advanced functions like reduce, filter, sorted, and key arguments. Additionally, we explore how lambda functions can be employed to craft anonymous functions for event handlers.

 

  • Use Lambda Functions with Reduce

     

    The reduce function, a higher-order function, accepts a binary function (a function with two arguments) and a list as inputs. It computes a single value, which is the outcome of sequentially applying the binary function to the elements of the list.

     

    For instance, consider the following code to compute the product of all elements in a list:

     

    from functools import reduce

    numbers = [1, 2, 3, 4, 5]

    product = reduce(lambda x, y: x*y, numbers)

    print(product) 

     

    # Output: 120

     

 

  • Use Lambda Functions with Filter

     

    The filter function, another higher-order function, accepts a function and a list as arguments. It produces a new list comprising only the elements from the original list for which the function returns True.

     

    For instance, to extract even numbers from a list, consider the following code:

     

    numbers = [1, 2, 3, 4, 5]

    even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

    print(even_numbers) 

     

    # Output: [2, 4]

     

    In this instance, the lambda function `lambda x: x % 2 == 0` is employed as the function argument within the filter function. The filter function calls this lambda function for each element in the numbers list, incorporating the element into the result list solely if the lambda function returns True.

     

 

  • Use Lambda Functions in the Key Argument of Various Functions

     

    Several functions in Python support a key argument, such as max, min, and sorted.

     

    The key argument is a function that accepts an element of the list and produces a value utilised as the sorting key. It also aids in comparison when employed with max and min functions.

     

    For instance, to identify the employee with the highest salary from a list of employees, consider the following code:

     

    employees = [{“name”: “John”, “salary”: 50000}, {“name”: “Jane”, “salary”: 55000}, {“name”: “Jim”, “salary”: 60000}]

    highest_salary_employee = max(employees, key=lambda x: x[“salary”])

    print(highest_salary_employee) 

     

    # Output: {“name”: “Jim”, “salary”: 60000}

     

    In this scenario, the lambda function `lambda x: x[“salary”]` is applied as the key argument within the max function. This lambda function is employed by the max function to retrieve the “salary” value for each employee in the employee’s list. Subsequently, these values are utilised for comparison to determine the employee with the highest salary.

     

 

  • Use Lambda Functions with the Sorted Function

     

    The sorted function is a pre-installed utility that arranges elements in a list. It includes an optional key parameter, which accepts a function. This function operates on each list element and provides a value utilised for sorting.

     

    For instance, if you wish to sort a list of dictionaries based on a particular key, you might employ the subsequent code:

     

    employees = [{“name”: “John”, “age”: 32}, {“name”: “Jane”, “age”: 27}, {“name”: “Jim”, “age”: 40}]

    sorted_employees = sorted(employees, key=lambda x: x[“age”])

    print(sorted_employees)

     

    # Output: [{“name”: “Jane”, “age”: 27}, 

    #          {“name”: “John”, “age”: 32}, 

    #          {“name”: “Jim”, “age”: 40}]

     

    In this instance, a lambda expression, specifically lambda x: x[“age”], is employed as the key parameter within the sorted function. The sorted function utilises this lambda expression to retrieve the “age” attribute from each dictionary in the employees’ list, using these values for sorting.

     

  • Use Lambda Functions to Create Anonymous Functions for Event Handlers

     

    Lambda functions can be utilised to generate anonymous functions for event handling in GUI programming or similar contexts.

     

    For instance, consider the following code snippet where a lambda function is employed to manage a button click event in Tkinter, a Python GUI programming toolkit:

     

    import tkinter as tk

     

    def on_button_click():

        print(“Button clicked!”)

     

    root = tk.Tk()

    button = tk.Button(root, text=”Click Me!”, command=lambda: print(“Button clicked!”))

    button.pack()

    root.mainloop()

     

    In this demonstration, we employ the lambda function `lambda: print(“Button clicked!”)` as the command argument for the Button widget within Tkinter. Upon clicking the button, the lambda function executes, leading to the printing of the message “Button clicked!” to the console.

    This showcases the adaptability and versatility of lambda functions, showcasing their utility across diverse contexts where anonymous functions are indispensable.

     

     

Limitations of Lambda Functions

 

While lambda functions offer a concise method for creating brief and straightforward functions, they come with certain constraints.

 

One significant limitation is their restriction to a single expression, prohibiting multiple statements or intricate control flow within them.

 

Moreover, lambda functions lack a specific name and can only be invoked at the point of their definition, reducing their flexibility compared to named functions.

 

Furthermore, the absence of a name for lambda functions can complicate debugging and comprehension of the code.

 

In practice, it’s advisable to employ named functions for complex operations and reserve lambda functions for brief and straightforward tasks.

 

Long Story Short

 

The lambda feature in Python exemplifies the language’s adaptability and sophistication. Its capacity to generate anonymous functions instantly empowers developers to compose succinct and effective code, boosting efficiency and refining development workflows. As you delve deeper into the Python landscape, mastering lambda functions emerges as a crucial asset in your repertoire.

 

Interested in enhancing your expertise? Explore the “Accelerator Program in Business Analytics and Data Science.” This extensive program allows students to immerse in the domains of data analytics and business intelligence. Seize the opportunity to advance your professional journey and unlock limitless possibilities in the captivating realm of data science.

 

 


Posted

in

by

Tags: