In Python, a lambda function is a small anonymous function that can have any number of arguments, but can only have one expression. It is defined using the lambda keyword, followed by the arguments and the expression to evaluate.
Here's a simple example of a lambda function:
add = lambda x, y: x + yprint(add(3, 4)) # Output: 7 |
In this example, add is a lambda function that takes two arguments (x and y) and returns their sum. The function is defined using the lambda keyword, followed by the arguments and the expression to evaluate (x + y).
Lambda functions are often used when you need to pass a function as an argument to another function, or when you want to define a simple function without giving it a name. For example, you might use a lambda function with the map() function to apply a transformation to each element in a list:
nums = [1, 2, 3, 4, 5]squared = list(map(lambda x: x**2, nums))
|
In this example, the map() function is used to apply a lambda function to each element in the nums list. The lambda function takes one argument (x) and returns its square. The result is a new list of squared values.