lambda: Anonymous, single-line functions for quick tasks.

Python Lambda Functions

Python lambda functions are small, anonymous functions created using the lambda keyword. These functions are typically one-liners designed for simple operations, often used as arguments in higher-order functions like map(), filter(), or sorted(). Lambda functions are also known as “inline functions” because they’re usually written where they’re used, without formally defining a function with def.

Syntax

The basic syntax of a lambda function:

lambda arguments: expression

- arguments: The inputs to the lambda function, which can be one or more parameters separated by commas.
- expression: A single expression that the lambda function returns.

Example 1: Basic Lambda Function

Here’s a simple example of a lambda function that adds two numbers.

add = lambda x, y: x + y
print(add(3, 5))

Output:

8

Example 2: Lambda Function with map()

Lambda functions are often used with map() to apply an operation to each item in an iterable, such as a list.

You can combine lambda functions with any() and all() to apply conditions across iterables.

numbers = [1, 2, 3, 4]
print(any(map(lambda x: x % 2 == 0, numbers))) # Output: True (because 2 and 4 are even)
print(all(map(lambda x: x > 0, numbers))) # Output: True (all numbers are positive)

Example 11: Lambda with Nested Lambda Functions

Lambda functions can even be nested, though this may reduce readability.

multiply = lambda x: lambda y: x * y
double = multiply(2)
print(double(5)) # Output: 10

Example 12: Lambda in Dictionaries

Lambda functions can be stored in dictionaries for quick command or function mappings.

operations = {
"add": lambda x, y: x + y,
"subtract": lambda x, y: x - y,
"multiply": lambda x, y: x * y
}
print(operations["add"](5, 3)) # Output: 8
print(operations["multiply"](5, 3)) # Output: 15

Use Cases for Lambda Functions

Quick One-Liner Functions: Ideal for small operations where defining a function would be overkill.

Higher-Order Functions: Lambda functions work well with functions like map(), filter(), and reduce() for functional programming tasks.

Sorting and Grouping Data: Use in sorted() or groupby() for custom sorting or grouping without needing separate helper functions.

Lambda functions provide flexibility and conciseness in Python programming. While powerful, they are best used for simple, short tasks since their anonymous nature can reduce readability for more complex operations.
«All Built in Functions in Python slice()