Python Lambda Functions

A lambda function is a small anonymous function that can have any number of arguments but only one expression. It is useful for short, simple functions that do not require a full function definition.

Syntax of a Lambda Function

lambda arguments: expression

Try It Now

Example: Lambda Function for Addition

add = lambda a, b: a + b
print(add(5, 3))  # Output: 8

Try It Now

Using Lambda Functions with map(), filter(), and reduce()

Example: Using map() with Lambda

The map() function applies a lambda function to each item in an iterable.

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

Try It Now

Example: Using filter() with Lambda

The filter() function filters elements based on a condition.

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

Try It Now

Example: Using reduce() with Lambda

The reduce() function performs a cumulative computation on a sequence.

from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # Output: 24

Try It Now

Key Takeaways

  • Lambda functions are small, anonymous functions used for quick operations.
  • They are often used with map(), filter(), and reduce().
  • Lambda functions can only contain a single expression.