Python Lambda

Python’s `lambda` function provides a compact way to create anonymous functions, allowing you to write quick, small functions without formally defining them. Unlike `def` functions, `lambda` functions are designed for single expressions and do not have statements within them. This makes `lambda` ideal for inline operations, often used with higher-order functions like `map()`, `filter()`, and `reduce()`.

Key Features

Anonymous: Lambda functions do not have a name, which makes them useful for short-term use.

Single Expression: They can only contain a single expression, which makes them limited compared to regular functions.

First-Class Citizens: They can be passed around just like regular functions.

Syntax of a `lambda` function:
lambda arguments: expression

1. Basic Usage of `lambda`

Example: Define a simple `lambda` function that takes a single argument and squares it:
square = lambda x: x ** 2
print("Square of 5:", square(5))

Output:
Square of 5: 25

Explanation: Here, `lambda x: x ** 2` is a function that takes one argument, `x`, and returns its square. This function is assigned to `square` and called as `square(5)`.

2. Multiple Arguments in `lambda`

`lambda` functions can accept multiple arguments:
add = lambda x, y: x + y
print("Sum of 3 and 7:", add(3, 7))

Output:
Sum of 3 and 7: 10

Explanation: Here, `lambda x, y: x + y` takes two arguments and returns their sum. This demonstrates how `lambda` can handle multiple arguments.

3. Using `lambda` with Higher-Order Functions

Using `lambda` with `map()`
The `map()` function applies a function to each item in an iterable. With `lambda`, we can define the function inline:
numbers = [1, 2, 3, 4]
squared = map(lambda x: x ** 2, numbers)
print("Squared numbers:", list(squared))

Output:
Squared numbers: [1, 4, 9, 16]

Using `lambda` with `filter()`
The `filter()` function applies a function that returns `True` or `False`, filtering items based on the condition:
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print("Even numbers:", list(even_numbers))

Output:
Even numbers: [2, 4]

Using `lambda` with `reduce()`
The `reduce()` function in the `functools` module applies a function cumulatively to the items in an iterable:
from functools import reduce

product = reduce(lambda x, y: x * y, numbers)
print("Product of all numbers:", product)

Output:
Product of all numbers: 24

Explanation: Here, `reduce()` multiplies all numbers in the list by applying the `lambda` function cumulatively.

4. `lambda` with Conditional Logic

`lambda` functions can use conditional (ternary) expressions:
max_value = lambda x, y: x if x > y else y
print("Maximum of 5 and 10:", max_value(5, 10))

Output:
Maximum of 5 and 10: 10

Explanation: The `lambda` function here checks if `x` is greater than `y`; if true, it returns `x`; otherwise, it returns `y`. This is useful for simple inline conditional checks.

5. Sorting with `lambda`

Using `lambda` with sorting functions like `sorted()` and `sort()` allows customized sorting:
students = [("Alice", 25), ("Bob", 20), ("Charlie", 23)]

# Sort by age
sorted_students = sorted(students, key=lambda student: student[1])
print("Students sorted by age:", sorted_students)

Output:
Students sorted by age: [('Bob', 20), ('Charlie', 23), ('Alice', 25)]

Explanation: The `lambda` function `lambda student: student[1]` extracts the second element (age) from each tuple, allowing `sorted()` to sort by age.

6. Advanced `lambda` Applications

Using `lambda` in Dictionaries
It can be useful to use `lambda` functions inside dictionaries for dynamic function mappings:
operations = {
    'add': lambda x, y: x + y,
    'subtract': lambda x, y: x - y,
    'multiply': lambda x, y: x * y,
    'divide': lambda x, y: x / y if y != 0 else 'undefined'
}

# Example usage
print("Add:", operations['add'](10, 5))
print("Divide:", operations['divide'](10, 0))

Output:
Add: 15
Divide: undefined

Explanation: This dictionary maps operation names to `lambda` functions, allowing dynamic function selection based on keys.

7. Using `lambda` with List Comprehensions and Conditional Expressions

In combination with list comprehensions, `lambda` can perform compact operations:
numbers = [5, 10, 15, 20]
squared_even = [(lambda x: x ** 2)(x) for x in numbers if x % 2 == 0]
print("Squared even numbers:", squared_even)

Output:
Squared even numbers: [100, 400]

Explanation: This comprehension squares only even numbers from the list using an inline `lambda`.

8. Limitations of `lambda`

While `lambda` is flexible, it has limitations:
- Single Expression Only: `lambda` can only contain one expression. For complex operations, use a regular `def` function.

- Lacks Readability for Complex Logic: `lambda` is suited for small, simple operations. Complicated logic in `lambda` functions can make code difficult to read.

For example, the following is not valid:
# Invalid lambda with multiple expressions
# complex_lambda = lambda x: x + 2; print(x)

Output:
SyntaxError: invalid syntax


Summary

The `lambda` function is a versatile tool in Python, allowing you to write concise, one-liner functions for quick operations. With applications in filtering, mapping, conditional logic, sorting, and higher-order functions, `lambda` provides powerful and flexible solutions for both beginners and advanced users, especially in functional programming contexts. However, for multi-step or complex logic, regular `def` functions are more suitable due to `lambda`'s single-expression limitation.

Previous: Python Functional Programming | Next: Python yield

<
>