Python Lambda Functions

In Python, a lambda function is a small anonymous function defined with the keyword lambda. Lambda functions can have any number of arguments but only one expression. These functions are often used when a simple function is needed for a short period of time, typically in cases like filtering, mapping, or reducing data.
Lambda functions are a powerful feature in Python, allowing you to create small anonymous functions on the fly. While they are limited to single expressions, their concise syntax makes them ideal for simple operations, especially when used with functional programming tools like filter(), map(), and reduce().

What is a Lambda Function?

A lambda function is a single-line function declared with the keyword lambda. It can take multiple arguments but only has one expression. The syntax for a lambda function is:

Syntax


lambda arguments: expression
            

Example 1: Using Lambda Function for Addition


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

Output

Sum: 8

Example 2: Using Lambda with filter() Function


# Example: Using lambda with filter()
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print("Even numbers:", even_numbers)
            

Output

Even numbers: [2, 4, 6]

Example 3: Using Lambda with map() Function


numbers = [1, 2, 3, 4]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print("Squared numbers:", squared_numbers)
            

Output

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

Example 4: Using Lambda with reduce() Function


from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print("Product of all elements:", product)
            

Output

Product of all elements: 24

Note: The reduce() function is available in the functools module.

Advantages of Lambda Functions

Limitations of Lambda Functions