Learning Sections show
Lambda Functions in Python
Lambda functions, also known as anonymous functions, are small, unnamed functions defined with the lambda
keyword. They can have any number of arguments but only one expression. Lambda functions are often used for short, throwaway functions that are not needed elsewhere in the code.
1. Basic Syntax
The syntax for a lambda function is:
lambda arguments: expression
Example:
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
2. Using Lambda with Built-in Functions
Lambda functions are commonly used with built-in functions like map()
, filter()
, and sorted()
.
Example with map()
:
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, numbers)
print(list(squared)) # Output: [1, 4, 9, 16, 25]
Example with filter()
:
numbers = [1, 2, 3, 4, 5]
even = filter(lambda x: x % 2 == 0, numbers)
print(list(even)) # Output: [2, 4]
Example with sorted()
:
points = [(2, 3), (1, 2), (4, 1), (3, 4)]
sorted_points = sorted(points, key=lambda point: point[1])
print(sorted_points) # Output: [(4, 1), (1, 2), (2, 3), (3, 4)]
3. Lambda Functions as Arguments
Lambda functions are often passed as arguments to other functions that take functions as parameters.
Example:
def apply_function(func, value):
return func(value)
result = apply_function(lambda x: x**2, 5)
print(result) # Output: 25