Python
    About Lesson

    Lambda Functions

    A lambda function is a small anonymous function defined with the lambda keyword. Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions are often used for short, throwaway functions that are not complex enough to warrant a full function definition.

    In Python, normal functions are defined using the def keyword, anonymous functions are defined using the lambda keyword.

    In Python, a lambda function can take several arguments, but can only have one expression.

     

    Syntax of Lambda Function

    lambda arguments: expression

    The expression is executed and the result is returned.

     

    Example

    lambda_add = lambda a, b: a + b
    				    
    print(add_lambda(20,20))

    In the above program, lambda a, b: a + b is the lambda function. Here a, b is the argument and a + b is the expression that gets evaluated and returned.

     

    Lambda Function with Multiple Arguments

    Lambda functions can take multiple arguments. Here’s an example that multiplies two numbers:

    multiply = lambda x, y: x * y
    print(multiply(2, 3)) # Output: 6

     

    Using Lambda with filter()

    The filter() function is used to filter items in an iterable (like a list) based on a function that returns True or False. Here’s an example using a lambda function to filter out even numbers from a list:

    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
    print(even_numbers) # Output: [2, 4, 6, 8, 10]

     

    Using Lambda with map()

    The map() function applies a given function to all items in an iterable. Here’s an example using a lambda function to square each number in a list:

    numbers = [1, 2, 3, 4, 5]
    squared_numbers = list(map(lambda x: x ** 2, numbers))
    print(squared_numbers) # Output: [1, 4, 9, 16, 25]

     

    Using Lambda with sort()

    You can also use a lambda function as the key argument in the sort() method to customize the sorting order. Here’s an example that sorts a list of tuples based on the second element:

    points = [(2, 3), (1, 2), (4, 1), (3, 5)]
    sorted_points = sorted(points, key=lambda x: x[1])
    print(sorted_points) # Output: [(4, 1), (1, 2), (2, 3), (3, 5)]

     

    Lambda functions in Python provide a quick and concise way to define small functions on the fly. They are particularly useful in situations where you need a simple function for a short period, such as with map(), filter(), and sort(). As lambda functions are powerful, they should be used sparingly to keep your code readable and maintainable. For more complex functions, it’s better to use regular def function definitions.