Applying Lambda Functions with Arguments
Using Lambda Functions with map()
The map()
function in Python applies a given function to each item in an iterable (such as a list, tuple, or string) and returns an iterator with the results. You can use lambda functions with map()
to perform simple operations on the items:
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, the lambda function lambda x: x ** 2
is used with the map()
function to square each number in the numbers
list.
Using Lambda Functions with filter()
The filter()
function in Python creates a new iterator with the elements from the input iterable for which the provided function returns True
. You can use lambda functions with filter()
to easily filter items based on a condition:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) ## Output: [2, 4, 6, 8, 10]
In this example, the lambda function lambda x: x % 2 == 0
is used with the filter()
function to select only the even numbers from the numbers
list.
Using Lambda Functions with reduce()
The reduce()
function in Python applies a function of two arguments cumulatively to the elements of a sequence, from left to right, to reduce the sequence to a single value. You can use lambda functions with reduce()
to perform complex operations:
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, the lambda function lambda x, y: x * y
is used with the reduce()
function to calculate the product of all the numbers in the numbers
list.
By combining lambda functions with built-in Python functions like map()
, filter()
, and reduce()
, you can write more concise and expressive code, especially for simple operations that don't require a full-fledged function definition.