Python Lambda Functions

Lambda functions are small, anonymous functions defined using the lambda keyword. They are often used for short, one-time operations.

Basic Syntax


    lambda arguments: expression
        

Lambda functions take any number of arguments, but they have only one expression. The result of the expression is returned implicitly.

Example 1: Simple Addition


    add = lambda x, y: x + y
    result = add(5, 3)
    print(result)  # Output: 8
        

Example 2: Squaring a Number


    square = lambda x: x * x
    print(square(4))  # Output: 16
        

Example 3: Using with `map()`


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

Explanation: `map()` applies the lambda function to each item in the list.

Example 4: Using with `filter()`


    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]
        

Explanation: `filter()` selects items in the list where the lambda function evaluates to `True`.

Example 5: Sorting a List of Tuples


    data = [(1, 'Shaista'), (3, 'Noorain'), (2, 'Arshiya')]
    sorted_data = sorted(data, key=lambda x: x[0])
    print(sorted_data)  # Output: [(1, 'Shaista'), (2, 'Arshiya'), (3, 'Noorain')]
        

Explanation: `sorted()` uses a lambda function as the `key` to specify how to sort the list of tuples.

Example 6: Simple Case Conversion


    string = "hello AIT"
    capitalize = lambda s: s.capitalize()
    print(capitalize(string))
        

Explanation: This shows how to perform a simple string operation.

Important Note

Lambda functions are concise and powerful, especially when used with higher-order functions like `map()` and `filter()`. However, they are best suited for simple operations. For more complex logic, a regular function is usually preferred for better readability.