In Python, the lambda
keyword is used to define anonymous functions. Anonymous functions are functions that are defined without a name. They are often used as a quick way to define a function for use in a single expression.
The map()
function is used to apply a function to every element in an iterable object, such as a list. It takes two arguments: the function to apply and the iterable object. The map()
function returns a new iterable object with the function applied to each element.
The filter()
function is used to filter the elements in an iterable object based on a certain criterion. It takes two arguments: the criterion function and the iterable object. The filter()
function returns a new iterable object containing only the elements that satisfy the criterion.
The reduce()
function is used to apply a function to the elements in an iterable object in a cumulative manner. It takes two arguments: the function to apply and the iterable object. The reduce()
function returns a single value that is the result of applying the function cumulatively to the elements in the iterable object.
Here is an example that uses all four of these functions to compute the sum of the squares of all the odd numbers in a list of numbers:
from functools import reduce numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # define a lambda function that squares a number square = lambda x: x * x # use the map() function to apply the square function to each element in the numbers list squared = map(square, numbers) # use the filter() function to keep only the odd numbers from the squared list odds = filter(lambda x: x % 2 == 1, squared) # use the reduce() function to sum the elements in the odds list sum = reduce(lambda x, y: x + y, odds) print(sum) # prints 85