Lambda Function in Python

Lambda function in python are a powerful and concise tool for writing short and anonymous functions. In this blog post, we will explore the basics of lambda functions and how they can be used effectively in your code.

A lambda function is a small anonymous function that can take any number of arguments, but can only have one expression. The syntax of a lambda function is as follows:

lambda arguments : expression

Lambda functions are usually used in combination with higher-order functions, such as “map()", "filter()" and "reduce()“. These functions are built-in Python functions that operate on other functions. For example, map() applies a function to each item of an iterable and returns a list of the results.

Let’s start by using a simple example to demonstrate the use of map() with a lambda function. Suppose we have a list of numbers and we want to square each number in the list. The following code shows how we can use a lambda function to accomplish this:

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

In this example, we pass the lambda function lambda x: x**2 as the first argument to map() and the list numbers as the second argument. The map() function then applies the lambda function to each item in the list, squares each number, and returns a list of the results.

Another common use for lambda functions is with the filter() function. The filter() function filters a sequence of items based on a condition. For example, if we have a list of numbers and we want to get only the even numbers, we can use the following code:

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

In this example, we pass the lambda function lambda x: x%2 == 0 as the first argument to filter() and the list numbers as the second argument. The filter() function then applies the lambda function to each item in the list, filtering only the even numbers, and returns a list of the results.

The reduce() function is another higher-order function that can be used with lambda functions. The reduce() function performs a cumulative operation on a sequence of items. For example, if we have a list of numbers and we want to find their product, we can use the following code:

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

In this example, we import the reduce() function from the functools module and pass the lambda function lambda x, y: x*y as the first argument to reduce() and the list numbers as the second argument. The reduce() function then applies the lambda function to the first two items in the list, calculates their product

Leave a Reply

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