What is the usage of lambda expressions?

A lambda expression is an anonymous function used to create simple functions, typically needed as parameters in a given situation. The basic syntax of a lambda expression is: lambda parameter list: expression.

For example, you can define an addition function using a lambda expression.

add = lambda x, y: x + y
print(add(1, 2))  # 输出: 3

The parameter list of a lambda expression can have multiple parameters separated by commas. The expression part can be any Python expression, which will be evaluated and returned as the function’s output.

Lambda expressions are commonly used with other functions such as map(), filter(), reduce(), etc., to process sequences.

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

In the given example, lambda expressions are used to calculate the square of each number, and the results are mapped to a new list using the map() function.

In conclusion, lambda expressions are mainly used in situations where a simple function is needed as a parameter, allowing for the quick definition of basic functions without having to formally define them.

bannerAds