Lambda or Anonymous Functions in Python

A lambda function in Python is a small, anonymous function defined with the lambda keyword. Unlike regular functions defined using def, lambda functions can have any number of arguments but can only have one expression. They are often used for short, throwaway functions and can be defined in a single line.

Key Points on Lambda Functions:

Syntax of Lambda Function:

Syntax Example

lambda arguments: expression

Example of Lambda Function in Python:

This example demonstrates a basic lambda function that squares a number.

Code Example 1

square = lambda x: x ** 2
        result = square(5)
        print(result)

Output

25

Using Lambda with Functions:

This example shows how to use a lambda function with the map function to double each number in a list.

Code Example 2

numbers = [1, 2, 3, 4, 5]
        doubled = list(map(lambda x: x * 2, numbers))
        print(doubled)

Output

[2, 4, 6, 8, 10]

Using Lambda with Filter:

This example demonstrates using a lambda function with the filter function to get even numbers from a list.

Code Example 3

numbers = [1, 2, 3, 4, 5, 6]
        even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
        print(even_numbers)

Output

[2, 4, 6]

Advantages of Using Lambda Functions:

Lambda functions provide a flexible way to define small functions without the overhead of a full function definition, making them particularly useful in functional programming paradigms.