Python 101: lambda function

In Python, a lambda function is a small anonymous function defined using the lambda keyword. It is typically used for short, simple operations that are needed temporarily, without defining a full function with the def keyword.

The syntax for a lambda function is:

lambda arguments: expression

Key Points:

  • lambda functions can have any number of arguments, but only one expression.
  • The expression is evaluated and returned automatically.
  • lambda functions are often used as arguments to higher-order functions (functions that take other functions as arguments), such as map(), filter(), and sorted().

Examples:

1. Basic Example of lambda

# Regular function
def add(x, y):
    return x + y

# Lambda function equivalent
add_lambda = lambda x, y: x + y

# Using the lambda function
result = add_lambda(5, 3)
print(result)  # Output: 8

2. Using lambda with map()

The map() function applies a function to all items in an input list (or iterable).

# List of numbers
nums = [1, 2, 3, 4, 5]

# Using lambda to square each number
squared = list(map(lambda x: x ** 2, nums))

print(squared)  # Output: [1, 4, 9, 16, 25]

3. Using lambda with filter()

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

# List of numbers
nums = [1, 2, 3, 4, 5, 6]

# Using lambda to filter even numbers
evens = list(filter(lambda x: x % 2 == 0, nums))

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

4. Using lambda with sorted()

The sorted() function sorts a list, and you can pass a custom key function using lambda to define how the elements should be sorted.

# List of tuples
points = [(2, 3), (1, 2), (4, 1), (3, 5)]

# Sort by the second element in each tuple
sorted_points = sorted(points, key=lambda x: x[1])

print(sorted_points)  # Output: [(4, 1), (1, 2), (2, 3), (3, 5)]

5. Using lambda with reduce()

The reduce() function (from the functools module) applies a function cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value.

from functools import reduce

# List of numbers
nums = [1, 2, 3, 4, 5]

# Using lambda to sum the numbers in the list
total = reduce(lambda x, y: x + y, nums)

print(total)  # Output: 15

When to Use lambda:

  • Short, simple operations: It’s ideal for short functions that are used temporarily.
  • Functional programming: Useful when passing functions to other functions like map(), filter(), sorted(), or reduce().

When Not to Use lambda:

  • Complex operations: For more complex logic, it’s better to use a regular function (def) for clarity and readability.

Let me know if you need more examples or explanations on how to use lambda functions!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *