The guide to Python's lambda Expressions; The What, Why, and How
In Python, a lambda function is a small anonymous function that can take any number of arguments but can only have one expression. The expression is evaluated and returned when the function is called.
Lambda functions are often used in conjunction with higher-order functions (functions that take other functions as arguments) such as filter(), map(), and reduce().
As you can see from the next examples, lambda functions are very useful for creating small, throwaway functions that are used for just a short amount of time. They can make your code more concise and readable, especially when used in combination with higher-order functions like map() and filter().
■ Map function with the lambda function
In the first example, the map() function takes a lambda function and a list of numbers as arguments. The lambda function squares each number in the list, and map() returns a map object containing the squared numbers, which is then converted to a list using the list() function.
# Example 1: Using lambda function with `map()`
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)
# Output: [1, 4, 9, 16, 25]■ Filter function with the lambda function
In the second example, the filter() function takes a lambda function and a list of numbers as arguments. The lambda function filters out all odd numbers, and filter() returns a filter object containing the even numbers, which is then converted to a list using the list() function.
# Example 2: Using lambda function with `filter()`
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
# Output: [2, 4]■ Reduce function with the lambda function
In the third example, the reduce() function from the 'functools' module takes a lambda function and a list of numbers as arguments. The lambda function multiplies two numbers at a time, starting from the first two numbers in the list and then multiplying the result by the next number in the list until all numbers have been processed. The reduce() function returns the final result, which is the product of all the numbers in the list.
# Example 3: Using lambda function with `reduce()`
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product)
# Output: 120■ Definition function with the lambda function
In the last example, the definition function takes a lambda function and number as arguments. The lambda function multiplies x and input number y and then returns the multiplied result. The definition function can be made of any kind and applied with the lambda function for many purposes.
# Example 4: Using lambda function as an argument to another function
def multiply(x):
return lambda y: x * y
double = multiply(2)
triple = multiply(3)
print(double(4))
print(triple(4))
# Output: 8
# Output: 12
댓글
댓글 쓰기