What is a lambda function. Provide an example

lambda function (also called an anonymous function) is a small, unnamed function defined using the lambda keyword in Python. It can take any number of arguments but must consist of a single expression, which is evaluated and returned.

Syntax:

python

lambda arguments: expression

Key Features:

  • No return statement (the expression is automatically returned).

  • Typically used for short, simple operations.

  • Often passed as arguments to higher-order functions like map()filter(), and sorted().

Example 1: Basic Lambda Function

python
# A lambda function that adds two numbers
add = lambda x, y: x + y

print(add(5, 3))  # Output: 8

Example 2: Using Lambda with sorted()

python
# Sort a list of tuples based on the second element
pairs = [(1, 9), (2, 5), (3, 7)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])

print(sorted_pairs)  # Output: [(2, 5), (3, 7), (1, 9)]

Example 3: Using Lambda with filter()

python
# Filter even numbers from a list
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))

print(evens)  # Output: [2, 4, 6]

Example 4: Using Lambda with map()

python
# Double each number in a list
numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))

print(doubled)  # Output: [2, 4, 6, 8]

When to Use Lambda Functions:

  • For short, one-time operations.

  • When passing a simple function as an argument to another function.

  • Avoid complex logic—use def for multi-line functions.

To Top